The Document Architecture

If your app opens and saves documents of a type peculiar to itself, you may want to take advantage of the document architecture. This architecture revolves around a class, UIDocument, that takes care of a number of pesky issues, such as the fact that loading or writing your data might take some time. Plus, UIDocument provides autosaving behavior, so that your data is written out automatically whenever it changes. Moreover, UIDocument is your gateway to allowing your documents to participate in iCloud, so your app’s documents on one of the user’s devices will automatically be mirrored onto another of the user’s devices.

Getting started with UIDocument is not difficult. You’ll start with a UIDocument subclass, and you’ll override two methods:

loadFromContents:ofType:error:
Called when it’s time to open a document from disk. You are expected to convert the contents value into a model object that your app can use, store that model object, and return YES. (If there was a problem, you’ll set the error: by indirection and return NO.)
contentsForType:error:
Called when it’s time to save a document to disk. You are expected to convert the app’s model object into an NSData instance (or, if your document is a package, an NSFileWrapper) and return it. (If there was a problem, you’ll set the error: by indirection and return nil.)

Your UIDocument subclass, then, in addition to its implementation of those two methods, will need a place to store and retrieve the data ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.