Four Random and Unrelated Core Data Tips

June 06, 2016

  1. Marcus Zarra is still the undisputed Core Data expert in my book. People who are new to Core Data tend get hung up around its threading model, but if you follow his advice you won’t have any problems. Even if you’re experienced with Core Data, you should watch his talk on the subject at least once. This related talk on networking is worth your time too.

  2. A new feature of iOS 8 is NSBatchUpdateRequest, which solves some of the problems with updating a set of objects that’s too large or slow to fetch into memory. But watch out! I didn’t even think about it at first, but NSBatchUpdateRequest completely bypasses the threading model mentioned above. There are still ways to safely use it, but my recommendation is to simply avoid it unless it’s something you legitimately need.

  3. Another new feature in iOS 9 is Core Data Constraints. Instead of following the fetch and create pattern when inserting data, you can set a constraint on an attribute and Core Data will check for existing objects with the same identifier. Handling conflicts seems messy though. I think I’m going to avoid this feature for now. Maybe I’ll change my mind, though.

  4. 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.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.