Friday, December 11, 2015

Double Core Data Accessors by Omitting @NSManaged

Trevor Squires:

If our implementation is not exposed to Objective-C, then Core Data will not find it at runtime, which means that, yes, Core Data will dynamically generate the accessor implementation for us.


This is why I now consider Swift to be the most satisfying language for using Core Data. The fact that (more expressive) types can’t be represented in Objective-C is a benefit, not a limitation.

Swift NSManagedObject subclasses can provide Swift-only accessors which happily coexist with Core Data’s dynamically-generated ones, and that feels like the best of both worlds.

Update (2016-06-07): Marc Charbonneau:

When you declare an @NSManaged var in your managed object subclass, normally it can be an Int, Bool, or Double. But not for Core Data primitive accessors! Primitive accessors (not to be confused with primitive types, I’m talking about methods that are a shorthand for primitiveValueForKey: … ) must be declared as an NSNumber. You don’t have to explicitly wrap your value in an NSNumber, you can still assign an Int or Double to your var and Swift will box it up for you. Not a big deal, but something to remember if you find your app crashing.

Comments RSS · Twitter

Leave a Comment