kiuzio2 kiuzio2 - 10 months ago 62
Swift Question

Proper way to store boolean in CoreData Swift

In my

I'm setting attribute:
notificationSet as Boolean
. Than in my model I am defining it as a
@NSManaged var notificationSet: NSNumber?
. When i want to save some item using this attribute I'm using it like this:

medicine.setValue(false, forKey: "notificationSet")

Is this a proper way to store booleans? It will be stored as a false ?

Answer Source

Yes, your KVC method will work, but it is bad practice. If you change the name of notificationSet, you will have to replace strings throughout your project. A typo in the key will compile fine and crash your app at runtime.

Instead, use NSManagedObject subclasses. Xcode can generate those for you automatically.

Also, it normally does not make sense to have a Boolean type as optional. Instead, give it a default value (e.g. "NO") in the model editor. The type is then NSNumber, rather than NSNumber?.

false should work automatically, but if you want to be explicit, you can use

medicine.notificationSet = NSNumber(bool: false)