user1178952
user1178952

Reputation:

Core Data managed objects in swift - is nil allowed?

I have created NSManagedObject subclasses for my model objects in swift.

Typically my pattern is to create an instance of an object and then set properties on it, then save.

The new objects have properties that are set to nil. They are not optionals, though. I thought in swift this wasn't allowed?

A lot of times I need to check for values, but if I try something like:

if (managedObject.property == nil) I crash.

Upvotes: 4

Views: 2988

Answers (2)

naudecruywagen
naudecruywagen

Reputation: 388

It seems Xcode doesn't automatically make managed vars optional when creating NSManagedObject subclasses. If the values are set as optional in the model, they should be optional in the subclass as well. (I set them as optional manually)

Model screenshot

class ClassWithOptionalName: NSManagedObject {

@NSManaged var name: String?

}

Upvotes: 7

Kim Sungyoo
Kim Sungyoo

Reputation: 39

Is managedObject.property optional value?

class CustomManagedObject: NSManagedObject {
    @NSManaged var aProperty: String?
                                    ^
}

Upvotes: 3

Related Questions