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

Allan  Macatingrao picture Allan Macatingrao · Aug 25, 2014 · Viewed 19.4k times · Source

I have a coredata entity named Record and has a property dateUpdated. I noticed that the generated NSManagedObject subclass has no optional mark (?)

CoreData Editor:

enter image description here

Generated Subclass:

enter image description here

Expected:

enter image description here

UPDATED: It's tedious in my part, because each time I want to regenerate the subclasses, it means I also need to update all optional values manually. Having a non-optional (without '?') in subclass lead me to check evalue before assigning, like example below:

// sample value:
// serverDateFormatter = "yyyy/MM/dd"
// dateString = ""    

// Branch is a subclass of Record (see above images)

var date = self.coreData.serverDateFormatter.dateFromString(dateString)
if date != nil
{
   branch.dateUpdated = date 
}

But if xcode can automatically set optional value in subclass with (?) I just need to do like this:

branch.dateUpdated = self.coreData.serverUTCDateFormatter.dateFromString(dateString)

In my case, I have bunch of properties I need to mark as optional manually.

Answer

Imanou Petit picture Imanou Petit · Aug 26, 2014

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.