mardi 26 mai 2015

Swift Unit Test EXC_BAD_ACCESS(code=1, address=0x8)

I have a managed object called Gift which has the properties

import Foundation
import CoreData

class Gift: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var price: NSNumber
    @NSManaged var location: String

}

Using a single unit test I then insert an entity into Core Data successfully (no error).

func testThatWeCanSaveGift() {
        let entity = NSEntityDescription.entityForName("Gift", inManagedObjectContext: managedObjectContext!)
        let gift = Gift(entity: entity!, insertIntoManagedObjectContext: managedObjectContext!)
        gift.name = "Test"
        gift.price = 10.0
        gift.location = "London"

        XCTAssertNotNil(gift, "Unable to create a gift")

        var error: NSError? = nil
        managedObjectContext?.save(&error)

        XCTAssertNil(error, "Failed to save the context with error \(error), \(error?.userInfo)")

To test that this was completely successful I then use a fetch request to return this data back.

        let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "Gift")
        var requestError: NSError? = nil
        if let gifts = managedObjectContext?.executeFetchRequest(fetchRequest, error: &requestError) {
            let aGift: NSManagedObject = gifts.first as! NSManagedObject
            //println("Gift name: \(aGift.name)")
            let string: String? = aGift.valueForKey("name") as? String
            println("Name: \(string)")
            var bGift: Gift = aGift as! Gift
            println("Name: \(bGift.name)")
            var a = 1
        }
    }

When I run this test it fails on the line that casts aGift to bGift var bGift: Gift = aGift as! Gift with the error EXC_BAD_ACCESS(code=1, address=0x8). However, I do get the results from the Core Data in the aGift but as a NSManagedObject

This only happens when I run the the code in a unit test, if I run it in the application it returns the correct information and casts it correctly.

What am I doing wrong for testing?

Aucun commentaire:

Enregistrer un commentaire