One of the longstanding criticisms of Core Data is how much code it takes to setup the infamous Core Data stack in your iOS or macOS app just so that you can create some instances of entities and save them to a persistent store. The frustration has spawned a number of blog posts outlining the latest, greatest way to setup your stack. Not long after the blog posts came the open source projects aimed at reducing the amount of boilerplate you’ve got to write and helping you avoid common mistakes.
With the release of iOS 10 and macOS 10.12 in many cases you can now forget about the blog posts and third party dependencies thanks to NSPersistentContainer. This one is a no-brainer and it would have been nice if Apple had included it back in the days of iOS 3.0 when they introduced Core Data.
Getting Started
Ready?
NSPersistentContainer.m
self.persistentContainer = [NSPersistentContainer persistentContainerWithName:@"Model"];
[self.persistentContainer loadPersistentStoresWithCompletionHandler:
^(NSPersistentStoreDescription* description, NSError* error) {
NSLog(@"%@ %@", description, error);
}];
In its most basic form, there’s really not much to it — you simply pass in the name of your Core Data model file and ask the NSPersistentContainer instance to load the related stores. There are also initializers that allow you to specify the NSManagedObjectModel yourself if you’d prefer.
So what does this get you?
- A viewContext property gives you an NSManagedObjectContext which has been configured for use on the main thread.
- Properties to access the underlying managedObjectModel and persistentStoreCoordinator.
- The newBackgroundContext method creates a new NSManagedObjectContext instance on a background thread.
- The performBackgroundTask method allows you to execute a block of code using a background context.
If this doesn’t meet your needs, and you need a custom setup, the existing APIs are still available, boilerplate and all.
How About Some Sample Code?
I’ve updated the ALAirports project from my earlier posts about Core Spotlight to use Core Data and create the stack using NSPersistentCoordinator. With a few simple changes to the ALAirport, ALAirportController, and the AppDelegate classes we’re able to import the airport data from the bundled CSV on the first launch of the app, and simply rely on the imported data in the persistent store from then on.
Header image by Frédéric Minne, licensed under Creative Commons.