I recently gave a talk at the Swift Language User Group (#SLUG) meetup at Realm in San Francisco. A video of the talk is now online over at Realm’s blog, where it is synced up with my slides. If you haven’t already seen it, go check it out! Realm does an absolutely amazing job with posting these meetup talks — in addition to the video and slides, there’s a full transcript and subtitles.
Talk summary
Realm’s notes and transcription are excellent, but I want to briefly to reiterate the main points of the talk here.
-
Put your model in its own framework. For example,
MyAppModel.framework
. This gives your models a clear namespace, makes your app modular, prepares your models for reuse elsewhere, and makes them easier to test. Do not add your models to the Test Target,import MyAppModel
instead. -
Write designated initializers for your
NSManagedObject
subclasses that use dependency injection. In other words, your initializer should be parameterized to receive values for all of its properties. This prevents your models from bypassing Swift’s strict initialization rules, because of@NSManaged
. Without doing this, you could end up with an instance of a model that is not fully initialized. Further, provide default parameter values where possible. -
Use Swift features. Make good use of optionals,
typealias
, andenum
to make your models more clear. Remember, Xcode does not properly generate classes with optional properties. -
Use JSQCoreDataKit! :) I plan on improving and adding to the framework as I use it in my side projects. If you are building an app using Swift and Core Data, please consider using it — contributions are more than welcome!
-
I’m interested in bringing type-safety and functional paradigms to Core Data. Currently, this approach means eschewing much of Objective-C’s dynamicism, which unfortunately leaves popular libraries like Mantle incompatible. This is mostly due to using designated initializers in Swift.
Other notes
There was a comment about iterating through the NSManagedObjectModel
. Details and discussion can be found at this gist.
Alejandro (@mephl) pointed out that NSBatchUpdateRequest
exists as of iOS 8. Awesome news! Anyone else feel like it is getting harder to keep track of all the changes and additions each year at WWDC?
Radar, or GTFO
I’ve filed the following radars for the issues I’ve experienced using Core Data in Swift. Duplicates are encouraged! And don’t forget to report anything else that you find.