Checking the nil Core Data property results in EXC_BAD_ACCESS

I have a simple subclass of NSManagedObject :

 @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 with if model.myProperty != nil with EXC_BAD_ACCESS . Why is this happening? It just started with Beta 5 and worked correctly with Beta 4.

The above class was automatically generated using Xcode, so they didn't add ? at the end of the property. However, manually adding ? to the end of the property fixes the problem ( @NSManaged var myProperty: String? ).

My question is: why does Xcode not automatically add a question mark to make it optional if it is marked as such in the diagram, and why is this not a problem in previous beta versions?

+6
source share
2 answers

To make it work, you have to do 2 things:

1) in a subclass of NSManagedObject add? to make 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 } 

Please note that if you forgot to add? in a subclass of NSManagedObject you have a compilation error.

+7
source

In fact, the Apple sample proposed in his Swift Programming Language manual,

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

Source: https://habr.com/ru/post/973372/


All Articles