UIManagedDocument for Core Data Apps

As someone who’s spent a lot of my career being the “Core Data guy” on many projects, I’m a bit embarrassed to admit I hadn’t taken much of a look at UIManagedDocument until now. UIManagedDocument came around with iOS 5, and I think because it seemed vaguely iCloud related (it’s not), and because none of the apps I was writing were document based (they don’t have to be), I never gave it a second thought. Now that I have, I can’t see any compelling reason to not use it for all of the apps I’m writing.

The best way to think of UIManagedDocument is as a replacement for the “Core Data Stack” class I’ve seen people write in a lot of different projects. What that class usually does is encapsulate set up of a Core Data stack into one class (NSManagedObjectContext, NSManagedObjectModel, and NSPersistentStoreCoordinator), often times with a private queue parent context for background saving. Doing this can make it as easy to set up a new stack as passing a file path and persistent store options to your class. What UIManagedDocument does is exactly everything I just said, and so it saves you having to write a bunch of boiler plate code — which is nice. Creating a new document just involves calling -[UIManagedDocument initWithFileURL:] and setting whatever persistent store options you like. You can now pass the document around as needed, or just use its managedObjectContext property to grab its context and inject that wherever you like.

But what if your app doesn’t work with documents in a way where having multiple persistent stores makes sense? Just create one document with a filename defined in your app. One good use case for using multiple documents is in an app where multiple accounts are allowed. If each account is its own document, than logging out just means deleting the file for that account. Also, since UIManagedDocument is easy to subclass, if you had an app that allows login from different services, it wouldn’t be a terrible place to put syncing logic that applies just to that service. If you were writing an app where you want to save the users data and sync through Service A, Service B or iCloud, you could write different document types to handle some specific differences for the two services and one that you place into an iCloud container.

I haven’t been using the class long enough to say that I’m sure I won’t run into any show stopping problems, but since the API is simple enough that they haven’t jumped out at me yet I’m only seeing upsides to using it right now.

Collin Donnell @collin