Swift + CoreData: Cannot Automatically Set Optional Attribute On Generated NSManagedObject Subclass

The optional checkbox in the Core Data Model Editor has been existing before Swift and its optionals where introduced. Apple states about it in its Core Data Programming Guide:

You can specify that an attribute is optional — that is, it is not
required to have a value. In general, however, you are discouraged
from doing so — especially for numeric values (typically you can get
better results using a mandatory attribute with a default value — in the
model — of 0). The reason for this is that SQL has special comparison
behavior for NULL that is unlike Objective-C’s nil. NULL in a database
is not the same as 0, and searches for 0 will not match columns with
NULL.

Thus, using Swift and Xcode 8, optional checkbox is (still) not related to the fact that you defined your properties as optionals or not in your managedObject subclasses. And don’t expect optional checkbox to have any impact on your NSManagedObject subclasses properties optional type when you create them using Editor > Create NSManagedObject Subclass.

That said, every time I need a property to have its optional checkbox checked in the Model Editor, I immediately put its NSManagedObject Subclass declaration as an optional.


Addendum

Mogenerator is able to automatically toggle your NSManagedObject subclass properties from non-optional to optional every time you change this option for each of your Entity’s attribute in the Data Model Inspector and rebuild your project.

Leave a Comment