Saturday, April 26, 2014

Document Revision History

This table describes the changes to iCloud Design Guide.
2014-04-09Updated "Designing for Core Data in iCloud" chapter to reference iCloud Programming Guide for Core Data.
2013-09-18Minor corrections and additions.
 Corrected text in Figure 1-4.
 Added information about coordinated reads of files that have not yet been downloaded to “Designing for Documents in iCloud.”
2012-09-19Added material throughout the document.
 Changed guidance on using wildcard characters in ubiquity container entitlement values, in “Request Access to iCloud Storage By Using Entitlements.”
 Reorganized and expanded the material in “Prepare Your App to Use iCloud.”
 Corrected Figure 1-4.
 Simplified the code listing in “Prepare Your App to Use the iCloud Key-Value Store.”
 Clarified the discussion around Figure 2-3.
 Added information to “Data Size Limits for Key-Value Storage.”
 Added two new sections in “Designing for Key-Value Data in iCloud”“Exercise Care When Using NSData Objects as Values” and“Don’t Use Key-Value Storage in Certain Situations.”
 Improved the discussion in “App Responsibilities for Using iCloud Documents.”
 Improved the discussion in “Designing for Core Data in iCloud.”
 Clarified the task steps in “Use Two Devices to Test Document Conflicts.”
 Added a new section about testing, “Start Fresh if Your iCloud Data Becomes Inconsistent During Development.”
2012-07-21Added material throughout the document.
2012-07-10New document that introduces the steps for incorporating iCloud support into your app.

Testing and Debugging Your iCloud App

Although no app is finished until it has been thoroughly tested and debugged, these steps are perhaps more important when you adopt iCloud: the number of user scenarios that your app must gracefully handle is greater. A user can have different versions of your app on different devices, or run your app on more than one device simultaneously. A user can turn on Airplane mode while a large file is uploading to iCloud. In rare cases, a user might log out of iCloud or switch to a different iCloud account.
This chapter helps orient you toward thinking about iCloud when testing and debugging your app.

Make Sure Your Device is Configured for iCloud

If things aren’t working as expected, first make sure that the preliminaries are correctly in place.
  • Ensure that your test devices are correctly provisioned for iCloud.
    Your device provisioning profile and app ID must be correctly configured for iCloud. Review “Adding Capabilities” in App Distribution Guide.
  • Ensure that your iCloud entitlement requests are correct.
    Without the appropriate entitlement requests in place in your Xcode project, your app has no access to its ubiquity containers or to key-value storage. Carefully review the information in “Request Access to iCloud Storage By Using Entitlements.”
    Ensure that when you access your app’s ubiquity containers, you are using fully-qualified entitlement values.

Take Latency Into Account

When testing, don’t expect changes to instantly propagate from one device to another.
You can programmatically determine if a file has made it to the iCloud servers by checking the value of its URL’s NSURLUbiquitousItemIsUploadedKeykey. Do this by calling the NSURL method getResourceValue:forKey:error:. The key’s Boolean NSNumber value contains true if the file has been successfully uploaded.
Likewise, you can programmatically determine if an iCloud file is present locally. Check the value of the NSURLUbiquitousItemIsDownloadedKey key of the corresponding URL by calling the NSURL method getResourceValue:forKey:error:.
In both cases, obtain the file URLs from your app’s NSMetadataQuery object, as described in “App Responsibilities for Using iCloud Documents.”

Monitor Your App’s Network Traffic

Keep an eye on network activity while testing your app, checking for undue amounts of network traffic. For iOS, use the “Network Activity Instrument”, described in Instruments User Reference. On a Mac, you can use the OS X Network Utility app.
If your app’s network traffic seems excessive, look for optimizations in your app design. For example, you may be able to design your document file package in a way to better support incremental uploads and downloads, as described in “Design for Network Transfer Efficiency.”

Use Two Devices to Test Document Conflicts

Real world use of your iCloud-enabled app can result in a wide range of conflict scenarios between versions of a document. Beyond that unavoidable truth, issues in an app’s logic can cause needless conflicts, as described in “Design for Persistent Document State.”
Here are some ideas for simulating real-world conflicts. To prepare for these tests, set up two devices to be connected to a single iCloud account. Implement your app to handle these scenarios and others that come to mind for your particular app.
To test document version conflicts with one device offline
To test document version conflicts with two devices offline
To test forward and backward compatibility of your document format
To test document management

Start Fresh if Your iCloud Data Becomes Inconsistent During Development

While you are developing an app, it is possible for data in the app’s ubiquity container to become inconsistent. If this happens, your app’s behavior can become inconsistent as well. If previously-working code is now not working, try emptying the ubiquity container for your app to start fresh.
You can empty your app’s ubiquity container using an iOS device or a Mac.
To empty the ubiquity container for your app, using an iOS device
To empty the ubiquity container for your app, using a Mac
If you provide an OS X version of your iCloud-enabled app, and you want to start completely fresh, also delete the contents of the app’s App Sandbox container on each Mac on which your app was installed. This ensures that any other app-specific data, that might have become inconsistent, is also removed. The path for an App Sandbox container on a Mac is:

Designing for Core Data in iCloud

Adopting iCloud Core Data storage makes the content in a shoebox-style app (like iPhoto) or a database-style app (like Bento) available on all of a user’s devices. See iCloud Programming Guide for Core Data for a complete implementation strategy.

Core Data Sends Incremental Changes to iCloud

Each instance of your app, on each device attached to an iCloud account, maintains its own local Core Data store file. When data changes locally, Core Data writes change log files to your app’s default ubiquity container.
The change log files, not the store file, are uploaded to iCloud and downloaded to each of a user’s other devices. When a change log arrives from another device attached to the same iCloud account, Core Data updates your app’s local copy of the SQLite database, based on the received change log. iCloud and Core Data ensure that each local database is updated with the same set of changes.
To learn more about using SQLite persistent stores with iCloud, see “Using the SQLite Store with iCloud” iniCloud Programming Guide for Core Data.

Managed Documents Support iCloud

The UIManagedDocument class is the primary mechanism through which Core Data stores managed documents in iCloud on iOS. TheUIManagedDocument class manages the entire Core Data stack for each document in a document-based app. Read “Using Document Storage with iCloud”in iCloud Programming Guide for Core Data to find out how to use managed documents in your app.
In OS X, Core Data integrates with the document architecture through the NSPersistentDocument class. However, in OS X v10.8, instances of this class do not provide specific support for iCloud.

Design the Launch Sequence for Your iCloud Core Data App

When you adopt iCloud, take special care when designing the launch sequence for your app. The following factors come into play and you must account for them:
  • The user might or might not have previously indicated a preference to use iCloud in your app; the local instance of your app might or might not have already established its initial store in a ubiquity container.
    As a first step in your launch sequence, read the local user defaults database using the shared NSUserDefaults object. During operation of your app, use that object to save user choices that you’ll need on next launch.
  • The user might log out of iCloud or switch to another account.
    If a user logs out of iCloud, or switches to another account, the ubiquity containers for the previously-used account are no longer available to your app.
  • The local Core Data store might be newer or older than the store on another device owned by the same user.
    During app launch, Core Data might need to reconcile the local store with change logs from iCloud. This can involve detection and resolution of duplicate records and conflicts. Testing is critical. To get started with some tips, refer to “Testing and Debugging Your iCloud App” as well as “Best Practices” and “Troubleshooting” in iCloud Programming Guide for Core Data.

Designing for Documents in iCloud

Adopting iCloud document storage makes your app’s documents available on all of a user’s devices.
To your app, a document (based on the UIDocument class in iOS or the NSDocument class in OS X) is an assemblage of related data that can be written to disk as a single file or as a file package. A file package, in turn, is a directory presented to the user as a single file, accessible to your app using anNSFileWrapper object.
Documents automatically implement most of the behavior expected of iCloud apps. Specifically, a document automatically ensures that local changes are safely coordinated with iCloud-originated changes. It does this by employing a file coordinator (NSFileCoordinator) object and by adopting the file presenter (NSFilePresenter) protocol. In OS X, starting in version 10.8 Mountain Lion, documents automatically provide open/save/rename UI and functionality; in iOS your app must implement these things.

How iCloud Document Storage Works

Your app uses iCloud document storage by reading and writing to a Documents subdirectory of one of its ubiquity containers. Figure 3-1 shows a simplified representation of local storage on a device, and shows data transfer to and from the iCloud servers.
Figure 3-1  Data and messaging interactions for iCloud apps
The system automatically grants your app access to the data in your app’s own sandbox container, but your app must request entitlements and employ iCloud storage APIs to use a ubiquity container. Figure 3-1 assumes that you have previously requested the appropriate entitlements, as explained in“Request Access to iCloud Storage By Using Entitlements.”
At step 1 in Figure 3-1, your app calls the NSFileManager method URLForUbiquityContainerIdentifier:, on a background thread, to set up iCloud storage and to obtain the URL for the specified ubiquity container. You must perform this step explicitly, except in the case of a document-based app in OS X, for which your document objects do this automatically on your behalf.
At step 2, the system grants your app access to the ubiquity container. Finally, at step 3, your app can read and write data to iCloud by accessing the ubiquity container.
Behind the scenes, the system manages the transfer of your app’s iCloud data to and from the iCloud servers in a way that preserves data integrity and consistency. In particular, the system serializes those transfers with your app’s file-system access, preventing conflicts from simultaneous changes. To support this serialization, iCloud apps must use special objects called file coordinators and file presenters. The name for serialized file system access using these objects is file coordination.
A document automatically uses a file coordinator (an instance of the NSFileCoordinator class) and adopts the file presenter (NSFilePresenter) protocol to manage its underlying file or file package. If you directly access a file or file package, such as to create it or delete it, you must use file coordination explicitly. For more information about using file coordination, see “The Role of File Coordinators and Presenters” in File System Programming Guide.
The first time your app adds a document’s on-disk representation to a ubiquity container, the system transfers the entire file or file package to the iCloud server, as shown in Figure 3-2.
Figure 3-2  Transferring a file to iCloud the first time
This transfer proceeds in two steps. In step 1 in the figure, the system sends the document’s metadata, which includes information such as the document name, modification date, file size, and file type. This metadata transfer takes place quickly. At some later point, represented in step 2, the system sends the document’s data.
Sending document metadata first lets iCloud quickly know that a new document exists. In response, the iCloud server propagates the metadata quickly to all other available devices attached to the same iCloud account. This lets the devices know that a new document is available.
After a document’s data is on the iCloud server, iCloud optimizes future transfers to and from devices. Instead of sending the entire file or file package each time it changes, iCloud sends only the metadata and the pieces that changed. Figure 3-3 shows a visual representation of an incremental upload.
Figure 3-3  Transferring just the file changes to iCloud
Again, file metadata is sent quickly to the iCloud servers, as shown in step 1, so that it can be propagated to other devices. Because the system tracks changes to the document, it is able to upload only the parts that changed, as shown in step 2. This optimization reduces iCloud network traffic and also reduces the amount of power consumed by the device, which is important for battery-based devices. As you learn later in this chapter, in “Design for Network Transfer Efficiency,” good file format design is essential to supporting incremental transfer.
Downloading of a document from iCloud to a device works as follows: Say a user creates a document on one device, as you saw in Figure 3-2. iCloud quickly sends that document’s metadata to all other devices attached to the same account. Step 1 of Figure 3-4 represents this transfer of metadata to one of those other devices.
Figure 3-4  Receiving a file from iCloud for the first time
The details of step 2 in this figure depend on the receiving device’s type.
An iOS device does not automatically download the new file, so your app must help. The steps to perform are described in “App Responsibilities for Using iCloud Documents.”
On a Mac, download is automatic for files created by other devices on the same account. For this reason, a Mac is sometimes referred to as a “greedy peer.” If your Mac app sees metadata for a new document but the document itself is not yet local, it is likely already being downloaded by the system on your app’s behalf.
Figure 3-5 depicts a device receiving updated metadata for a changed document that the device has previously downloaded. New metadata is received, in this scenario, because the user made a change to the document on another of their devices.
Figure 3-5  Receiving changed data from iCloud
When the device receives updated metadata (step 1), the system responds by asking iCloud to send the corresponding incremental data right away (step 2).

App Responsibilities for Using iCloud Documents

Changes to your app’s documents can arrive from iCloud at any time, so your app must be prepared to handle them. The NSDocument class in OS X does most of this work for you, while in iOS there is more for your app to handle explicitly. Follow these guidelines:
  • Enable Auto Save. For your app to participate with iCloud, you must enable Auto Save.
    In iOS, enable Auto Save by registering with the default NSUndoManager object or else by calling the UIDocument method updateChangeCount: at appropriate points in your code, such as when a view moves off the screen or your app transitions to the background.
    In OS X, enable Auto Save by overriding the NSDocument class method autosavesInPlace to return YES.
  • In iOS, actively track document location. Each instance of your iOS app must be prepared for another instance to move, rename, or delete iCloud-based documents. If your app persistently stores a URL or path information to a file or file package, do not assume that the item will still be there the next time you attempt to access it.
    In iOS, employ an NSMetadataQuery object, along with file coordination, to actively track the locations of your documents. Early in your app’s launch process, instantiate and configure a metadata query object, start it, and register for its NSMetadataQueryDidUpdateNotification notification. Implement the presentedItemDidMoveToURL: method and the presentedItemURL property to allow your app to respond to pushed changes from iCloud. Refresh your app’s model layer and update your app’s user interface elements as needed.
    For a working example of using a metadata query in iOS, see “Searching for iCloud Documents” in Your Third iOS App: iCloud. For details on using metadata queries, see File Metadata Search Programming Guide.
  • In OS X, do not actively track document location. The Open and Save dialogs in a document-based Mac app automatically track the locations of iCloud-based documents; you typically do not need to use an NSMetadataQuery object. For example, if a user renames or moves a document while working on one device, instances of your app running on other devices automatically pick up those changes by way of the document architecture.
  • In iOS, actively download files when required. Items in iCloud but not yet local are not automatically downloaded by iOS; only their metadata is automatically downloaded. The initial download of new iCloud-based documents requires your attention and careful design in your app. After you explicitly download such an item, the system takes care of downloading changes arriving from iCloud.
    Consider keeping track of file download status as part of your iOS app’s model layer. Having this information lets you provide a better user experience: you can design your app to not surprise users with long delays when they want to open a document that is not yet local. For each file (or file package) URL provided by your app’s metadata query, get the value of the NSURLUbiquitousItemIsDownloadedKey key by calling the NSURL methodgetResourceValue:forKey:error:. Reading a file that has not been downloaded can take a long time, because the coordinated read operation blocks until the file finishes downloading (or fails to download).
    For a file (or file package) that is not yet local, you can initiate download either when, or before, the user requests it. If your app’s user files are not large or great in number, one strategy to consider is to actively download all the files indicated by your metadata query. For each file (or file package) URL provided by the query, make the corresponding item local by calling the NSFileManager method startDownloadingUbiquitousItemAtURL:error:. If you pass this method a URL for an item that is already local, the method performs no work and returns YES.
  • In iOS, respond to, and resolve, document version conflicts as needed. The document architecture supports conflict resolution by nominating a winning NSFileVersion object, but it is your iOS app’s responsibility to accept the suggestion or override it. You can rely on this automatic nomination most of the time, but your app should be prepared to help as needed.
    A conflict arises when two instances of your iOS app, running on two different devices, attempt to change a document. This can happen, for example, if two devices are not connected to the network, a user makes changes on both of them, and then reconnects both devices to the network.
    When an iOS document’s state changes, it posts a UIDocumentStateChangedNotification notification. On receiving this notification, query the document’s documentState property and check if the value is UIDocumentStateInConflict. If you determine that explicit resolution is needed, resolve the conflict by using the NSFileVersion class. Enlist the user’s help, if necessary; but when possible, resolve conflicts without user involvement. Keep in mind that another instance of your app, running on another device attached to the same iCloud account, might resolve the conflict before the local instance does.
    When done resolving a conflict, be sure to delete any out-of-date document versions; if you don’t, you needlessly consume capacity in the user’s iCloud storage.
  • In OS X, rely on the system to resolve document conflicts. OS X manages conflict resolution for you when you use documents.
  • In OS X, avoid deadlocks resulting from modal UI elements. It is possible for a document change to arrive from iCloud while your app is presenting a modal user interface element, such as a printing dialog, for the same document. If that incoming change requires its own modal interface, such as for conflict resolution, your app can deadlock.
  • Always use a file coordinator to access an iCloud file or file package. A document uses a file coordinator automatically, which is one of the great benefits of using documents when designing for iCloud.
    A document-based iOS app, however, must use a file coordinator explicitly when operating on a document’s underlying file; that is, when moving, renaming, duplicating, or deleting the file. For these operations, use methods from the NSFileManager class within the context of a file coordinator writing method. For more information, see “The Role of File Coordinators and Presenters” in File System Programming Guide.
    Most document-based OS X apps should employ the built-in app-centric document viewing UI that appears when opening or saving documents. Even if your OS X app needs to present documents programmatically to the user, do not programmatically move, rename, or delete documents. It’s up to the user to perform those operations using the Finder, the built-in document renaming UI, or the built-in iCloud “move” menu items in the File menu.
  • Don’t let users unintentionally share information. Unlike iOS users, OS X users have direct access to the file system. For example, if you keep an undo stack within your document format’s file package, that information is accessible to a user viewing your app’s document in OS X.
    This issue predates iCloud, but may not be familiar to you if you are primarily an iOS developer.
    When designing your document format, carefully consider which information your users would not want to share—for example, in an emailed version of the document. Instead of placing such information within the file package, associate it with the document but store it outside of the Documentssubdirectory in the ubiquity container (see Figure 1-2).
  • Make your documents user-manageable, when appropriate. Place files in the Documents subdirectory of an iCloud container to make them visible to the user and make it possible for the user to delete them individually. Files you place outside of the Documents subdirectory are grouped together as “data.” When a user visits System Preferences (OS X) or Settings (iOS), they can delete content from iCloud. Files that you place outside of theDocuments subdirectory can be deleted by the user only as a monolithic group.
    The choice of whether or not to use the Documents subdirectory depends on your app design. For example, if your app supports a user creating and naming a document, put the corresponding document file in the Documents subdirectory. If your app does not let users interact with files as discrete documents, it’s more appropriate to place them outside of the Documents subdirectory.

Designing a Document File Format for iCloud

Choices you make in designing your document format can impact network transfer performance for your app’s documents. The most important choice is to be sure to use a file package for your document format.
If you provide versions of your app for iOS and Mac, design your document file format to be cross-platform compatible.

Design for Network Transfer Efficiency

If your document data format consists of multiple distinct pieces, use a file package for your document file format. A file package, which you access by way of an NSFileWrapper object, lets you store the elements of a document as individual files and folders that can be read and written separately—while still appearing to the user as a single file. The iCloud upload and download machinery makes use of this factoring of content within a file package; only changed elements are uploaded or downloaded.
Register your document file format, and its associated filename extension, in your app’s Info.plist property list file in Xcode. Specifically, use the“CFBundleDocumentTypes” in Information Property List Key Reference key to specify the file formats that your app recognizes and is able to open. Specify both a filename extension and a uniform type identifier (UTI) corresponding to the file contents. The system uses this information to associate file packages to your app, and, in OS X, to display file packages to the user as though they were normal files.

Design for Persistent Document State

Many document-based apps benefit from maintaining state on a per-document basis. For example, a user of a vector-based drawing app would want each document to remember which drawing tool was most recently used and which element of the drawing was selected.
There are two places you can store document-specific state:
  • Within the file package (or flat-file format) for a document. This choice supports keeping the state together with the document if, for example, a user sends it by email.
  • Associated with the document but outside of its file package (or file format). This choice supports cases in which a user would not want to share information. But, being outside of the data managed by your document objects, such state is not tracked by a document’s conflict resolution functionality. It is up to you to do so.
Whichever scheme you choose, take care, in an app that supports editing, to never save document state unless document content was edited. Otherwise, you invite trivial and unhelpful conflict scenarios that consume network bandwidth and battery power.
For example, imagine that a user had been editing a long text document on their iPad, working on page 1. A bit later, they open the document on their iPhone and scroll to the last page. This badly-behaved example app aggressively saves the end-of-document scroll position—even though the user made no other changes. When the user later opens the document on their iPad to resume editing, there is a needless conflict due to scroll position data. The system has marked the document as in conflict (UIDocumentStateInConflict), and the newer version (automatically nominated as the conflict winner) is the one scrolled to the last page. To be a well-behaved iCloud app, this text editor should have ignored the change in scroll position on the iPhone because the user did not edit the content.
Think through various usage scenarios for your app, and design accordingly to improve user experience. Take care with state like:
  • Document scroll position
  • Element selection
  • Last-opened timestamps
  • Table sort order
  • Window size (in OS X)
A strategy to consider is to save such state but only when the user has also made a change that deserves saving. In OS X, the built-in Resume feature provides all the state saving behavior that most document-based apps need. If you want additional control, you can take advantage of theNSChangeDiscardable document change type.

Design for Robustness and Cross-Platform Compatibility

Keep the following factors in mind when designing a document file format for iCloud:
  • Employ a cross-platform data representation. Like-named classes—those whose prefixes are “UI” for iOS and “NS” for OS X—are not directly compatible. This is true for colors (UIColor and NSColor), images (UIImage and NSImage), and Bezier paths (UIBezierPath and NSBezierPath), as well as for other classes.
    For example, an OS X NSColor object is defined in terms of a color space (NSColorSpace), but there is no color space class in iOS.
    If you employ such a class in a document format property, you must devise an intermediate iCloud representation that you can faithfully reconstitute into the native representation on either platform, as depicted in Figure 3-6.
    Figure 3-6  Using a cross-platform data representation
    In step 1, your OS X app stores an in-memory document object to disk, converting each platform-specific data type to an appropriate cross-platform representation. Steps 2 and 3 show the data uploaded and then downloaded to an iOS device. In step 4, the iOS version of your app extracts the data, converting from the intermediate representation into iOS-specific data types, thereby constructing a UIDocument-based version of the originalNSDocument-based object.
    When storing a document from your iOS app for later viewing on either platform, you’d reverse the process shown in Figure 3-6—starting by storing your iOS document using a cross-platform data representation.
    For each platform-specific data type you employ in your document format, check if there is an appropriate, lower-level data type shared by both platforms that you can use in the intermediate representation. For example, each color class (UIColor and NSColor) has an initialization method that lets you create a color object from a Core Image CIColor instance.
    When preparing data for writing to iCloud, convert to the intermediate representation; when reading an iCloud-based file, convert from the intermediate representation. If you call methods from NSCoder or its concrete subclasses to encode and decode your document’s object graph, perform these conversions within those methods.
  • Take platform-specific coordinate systems into account. The default screen coordinate systems in iOS and OS X are different, leading to differences in how you draw and in how you position views. Take this into account when storing and extracting screen coordinate information with your cross-platform representation. For more information, see “Coordinate Systems and Drawing in iOS” in Drawing and Printing Guide for iOS.
  • Always use case-insensitive filenames. OS X, by default, and for nearly all users, employs a case-insensitive file system. For example, the filemydoc.txt and the file MyDoc.TXT cannot both exist within the same directory in OS X. By contrast, iOS treats those file names as being different.
    To make your document file format cross-platform compatible, you must read and write files in a case-insensitive manner.
  • Use a format version number. Because you may want to change your document format in the future, design a format version numbering scheme and apply the version number as a property of the document format.
    Versioning your document format has always been a good idea, but with iCloud and cross-platform formats, it’s even more important. For example, an iCloud user is likely to have multiple devices on which they can view their content; but the user might not conscientiously update your app on all of their devices at once. So, for example, a user’s Mac might have the newest version of your OS X app but their iPad might have a year-old version of your iOS app.
    An early version of your app might be iOS-only; when you later distribute an OS X version, you’ll likely want to modify the document format. By embedding the format version within each document, your code can gracefully handle documents regardless of their version. You might, for example, make an old, iOS-only format read-only in OS X. Think through various scenarios involving multiple devices on each platform, each running a different version of your app. Make sure that you provide the best possible user experience for iCloud-based documents.
For more information about techniques for designing file formats, see “Choosing Types, Formats, and Strategies for Document Data” in Document-Based App Programming Guide for iOS or “Handling a Shared Data Model in OS X and iOS” in Document-Based App Programming Guide for Mac.

Document-Based Workflows

Table 3-1 lists some typical workflows for document-based apps. For each workflow, the table lists the primary classes you typically use, along with a brief description of the task.
Table 3-1  Typical document-based app workflows
Create a new standard documentUIDocument (iOS)
NSDocument (OS X)
Use a document object to create and manage the data structures in your document format. The document classes automatically support saving new documents to a ubiquity container or to local storage.
Create a new Core Data documentUIManagedDocument(iOS)
NSPersistentDocument(OS X)
Use the Core Data document subclasses to create and manage your Core Data stores. For details, see “Designing for Core Data in iCloud.”
Obtain URLs to iCloud documentsNSMetadataQuery (iOS)
Automatic (OS X)
In iOS, use a metadata query object to locate and obtain live-updated information on iCloud documents.
In OS X v10.8 or later, a document Open dialog uses a metadata query automatically.
Prompt the user to open a document.Custom UI (iOS)
Automatic as part of the document architecture (OS X)
In iOS, your app is directly responsible for presenting a selection UI for user documents in a simple and clean way that fits well with the rest of the app design.
In OS X v10.8 or later, the Open command in a document-based app presents a dialog that lets the user select iCloud files.
Handle version conflictsUIDocument,NSFileVersion (iOS)
Automatic (OS X)
In iOS, documents detect and notify you about conflicts. Use NSFileVersion objects (one per revision of a document) to resolve them, as needed.
Move, duplicate, and delete iCloud-based documentsNSFileCoordinator
Manipulate files on disk using the NSFileManager class, and always within the context of a file coordinator object.
For details on how to perform the preceding workflows, look in the document-based programming guide for the platform you are targeting. For iOS, seeDocument-Based App Programming Guide for iOS. For Mac, see Document-Based App Programming Guide for Mac.