Generated Swift NSManagedObject subclasses are dangerous

Number:rdar://20153926 Date Originated:13-Mar-2015 11:06 AM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode 6.3b3
Classification:Serious Bug Reproducible:Always
When using Core Data with Swift, Xcode's generated NSManagedObject subclass files are dangerous and likely to cause app crashes. This can occur whenever a Core Data attribute is marked as "optional" in the managed object model file. In the generated NSManagedObject subclass, these attributes are represented as non-optional properties. As a result it's possible to have a nil value for an object property which is not considered to be optional by Swift.

Steps to Reproduce:
1. Start a new Swift project that uses Core Data
2. Create an entity with at least one attribute marked as "optional" in the managed object model.
3. Have Xcode generate a custom NSManagedObject subclass file for this entity.

Expected Results:
Since the attribute is optional to Core Data, it would also be optional in the Swift property in the new subclass file.

Actual Results:
The property is not optional in the new subclass file. This creates a situation where it's entirely valid to have an instance of the class in which there's a nil value for a non-optional Swift property. Swift normally requires that non-optional properties have values by the time an object has been initialized, but Xcode's generated code allows this rule to be violated. This is likely to lead to app crashes since Swift code will assume that the non-optional property has a non-nil value.

Xcode 6.3 (6D543q)
OS X 10.10.2 (14C1510)

Sample project attached. In this project there's a single entity called Event that has three attributes. Two are required, one is optional. In the generated subclass Event.swift, all three are non-optional properties.

In MasterViewController's configureCell method there are a couple of ways of assigning the table view cell's text. Since the "timeStamp" attribute is not optional in the managed object model, this is safe:

        cell.textLabel!.text = object.timeStamp.description

However the "summary" attribute is optional in the managed object model but not optional in Event.swift. As a result this version crashes:

        cell.textLabel!.text = object.summary

The definition in Event.swift guarantees that "summary" has a value, but Core Data allows it to not have a value, and this conflict causes the crash.

I don't expect Xcode's generated code to be as complete as something like mogenerator's code, but I would expect it to at least be safe to use.


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!