Check if property is set in Core Data?

Update for Xcode 7: This issue has been solved with Xcode 7 beta 2.
Optional Core Data properties are now defined as optional properties
in the managed object subclasses generated by Xcode. It is no longer
necessary to edit the generated class definition.


(Previous answer:)

When creating the NSManagedObject subclasses, Xcode does not define optional properties for those attributes which are marked as “optional” in the Core Data model inspector.
This looks like a bug to me.

As a workaround, you can cast the property to
an optional (as String? in your case) and then test it with optional binding

if let notice = someManagedObject.noticeText as String? {
    println(notice)
} else {
    // property not set
}

In your case that would be

if let notice = formQuestions[indexPath.row].noticeText as String? {
    println(notice)
} else {
    // property not set
}

Update: As of Xcode 6.2, this solution does not work anymore
and crashes with a EXC_BAD_ACCESS runtime exception
(compare Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails)

The “Old answer” solution below still works.


(Old answer:)

As @Daij-Djan already stated in a comment, you have to define the property for an
optional Core Data attribute as optional or implicitly unwrapped optional:

@NSManaged var noticeText: String? // optional
@NSManaged var noticeText: String! // implicitly unwrapped optional

Unfortunately, Xcode does not define the optional properties correctly when creating
the NSManagedObject subclasses, which means that you have to re-apply the changes
if you create the subclasses again after a model change.

Also this seems to be still undocumented, but both variants worked in my test case.

You can test the property with == nil:

if formQuestions[indexPath.row].noticeText == nil {
    // property not set
}

or with an optional assignment:

if let notice = formQuestions[indexPath.row].noticeText {
    println(notice)
} else {
    // property not set
}

Leave a Comment