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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With