Search code examples
iosswiftcore-datansmanagedobjectoptional-parameters

Core data | automatically generated String and Date attributes are optional even when not marked in swift


I have noticed the date and string attributes are always created as optionals in swift in auto-generated classes even when optional attribute is not selected.

In the apple documentation also, all Date and string are shown as optional in example

In Swift, you declare the properties using the @NSManaged keyword:

class MyManagedObject: NSManagedObject {

@NSManaged var title: String?

@NSManaged var date: NSDate?

}

Currently using swift 3.2 I dont want certain string attributes to be non- optional. What is the best way to make it as mandatory?


Solution

  • Two options

    • Edit the MyManagedObject to make them non-optional. This means you need to maintain this class yourself and do any changes both in the core data model and the class
    • Create a protocol (or sub class) with same attributes (you need to give them new names) but non-optional and implement this protocol in a separate extension to get and set original attributes and then use this protocol rather than MyManagedObject in your code.

    If your data model is stable and won't be changed that much the first option is probably best.