Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for nil Core Data property results in EXC_BAD_ACCESS

I have a simple NSManagedObject subclass:

@objc class MyModel: NSManagedObject {
    @NSManaged var myProperty: String
}

However, the following code:

var model = NSEntityDescription.insertNewObjectForEntityForName("MyModel", inManagedObjectContext: managedObjectContext) as MyModel

assert(model != nil) // passes

if model.myProperty != nil { //crashes
    println("not nil")
}

crashes at if model.myProperty != nil with a EXC_BAD_ACCESS. Why is this happening? This only started happening with Beta 5, and worked properly with Beta 4.

The above class was automatically generated using Xcode, so they did not add a ? to the end of the property. However, manually adding a ? to the end of the property does resolve the issue (@NSManaged var myProperty: String?).

My question is, why doesn't Xcode automatically add the question mark to make it optional if it is marked as such in the schema, and why was this not an issue in previous betas?

like image 261
Snowman Avatar asked Aug 05 '14 14:08

Snowman


1 Answers

To make it work you should do 2 things :

1) in the NSManagedObject subclass add ? to made the property optional

@objc class MyModel: NSManagedObject {
    @NSManaged var myProperty: String? // <-- add ? here
}

2) in your implementation as suggested in the previous answer

if let aProperty = model.myProperty? {
    // do something with aProperty
}

Note that if you forgot to add ? in the NSManagedObject subclass you we have compilation error.

like image 100
ant_one Avatar answered Oct 18 '22 01:10

ant_one