␡
- Setting Up an iCloud-Compatible Project
- How iCloud Works
- iCloud Container Folders
- Recipe: Trying Out iCloud
- Working with UIDocument
- Recipe: Subclassing UIDocument
- Metadata Queries and the Cloud
- Handy Routines
- Recipe: Accessing the Ubiquitous Key-Value Store
- Recipe: UIManagedDocument and Core Data
- Summary
This chapter is from the book
Recipe: Subclassing UIDocument
At a minimum, each document instance inherits two core responsibilities: to produce its actual document data on demand and to update itself to new data in response to iCloud refreshes. When you subclass UIDocument, you must implement two methods. Recipe 18-2 presents the barest-bones document subclass that you might create:
- The loadFromContents:error: method brings new content to the class, allowing it to update its internal data. When it receives its new data, it pings an informal delegate to let it know that it’s a good time to reload the image.
- The contentsForType :error: method gets called whenever the user saves data locally. Here, you produce a data representation of your document that can be stored to the cloud, allowing you to publish that data ubiquitously.
This recipe demonstrates the simplicity of creating a cloud-based document. With just these two methods, you can store nearly any kind of data ubiquitously.
Recipe 18-2 Simple Cloud Document Class
@interface ImageDocument : UIDocument @property (strong) UIImage *image; @property (weak) id delegate; @end #define SAFE_PERFORM_WITH_ARG(THE_OBJECT, THE_SELECTOR, THE_ARG) (([THE_OBJECT respondsToSelector:THE_SELECTOR]) ? [THE_OBJECT performSelector:THE_SELECTOR withObject:THE_ARG] : nil) @implementation ImageDocument @synthesize image, delegate; - (BOOL) loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError { NSLog(@"Loading external content"); self.image = nil; if ([contents length] > 0) self.image = [[UIImage alloc] initWithData:contents]; if (delegate) SAFE_PERFORM_WITH_ARG(delegate, @selector(imageUpdated:), self); return YES; } - (id) contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError { NSLog(@"Publishing content"); return UIImageJPEGRepresentation(self.image, 0.75f); } @end