Search code examples
iosxcodeswiftcore-data

Xcode NSManagedObject subclass contains optionals when they are marked as non-optional


I have a core data entity named Film which has properties title and date. I noticed that the generated NSManagedObject subclass contains optional NSManaged properties even though I marked the properties as non optional in the core data inspector.

enter image description here

enter image description here

Can I can manually change it as non-optional property or is it a better choice to leave it as optional? Why?


Solution

  • "Optional" means something different to Core Data than it does to Swift.

    • If a Core Data attribute is not optional, it must have a non-nil value when you save changes. At other times Core Data doesn't care if the attribute is nil.
    • If a Swift property is not optional, it must have a non-nil value at all times after initialization is complete.

    Making a Core Data attribute non-optional does not imply that it's non-optional in the Swift sense of the term. That's why generated code makes these properties optional-- as far as Core Data is concerned, it's legal to have nil values except when saving changes.

    Update: After writing this answer I wrote a deep dive blog post explaining things in more detail: https://www.atomicbird.com/blog/clash-of-the-optionals/