Database Reference
In-Depth Information
Now that we know we have data and metadata we create an NSMutableDictionary called wrappers
that we will use in the following lines. We then call encodeObject:toWrappers:withKey: for both our
data and metadata passing the respective key. Finally, we create an NSFileWrapper and instantiate
it with our wrappers dictionary by calling initDirectoryWithFileWrappers: . Then we return our file
wrapper.
Next we will add the data reading methods:
#pragma mark - Document Reading Methods
-(BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError *__autoreleasing *)
outError {
_fileWrapper = (NSFileWrapper *)contents;
_data = nil;
_metadata = nil;
return YES;
}
- (id)decodeObjectFromWrapperWithKey:(NSString *)key {
NSFileWrapper *fileWrapper = [_fileWrapper.fileWrappers objectForKey:key];
if(!fileWrapper)
return nil;
NSData *data = [fileWrapper regularFileContents];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
return [unarchiver decodeObjectForKey:@"DATA"];
}
Starting with loadFromContents:ofType:error: we take the contents parameter, which is an
NSFileWrapper , and assign it to our local NSFileWrapper property. We use this later to lazily load our
metadata and data. Next we set our _data and _metadata objects to nil also because we will lazily
load them when needed. Finally, we return YES to tell the system there was no problem loading the
document.
The next method decodeObjectFromWrapperWithKey : simply grabs the fileWrapper for the
specific object using the passed in key. If it was unable to obtain a fileWrapper , it returns nil
and ends execution. With the retrieved fileWrapper we fetch the NSData object by using the
regularFileContents method against NSFileWrapper . We then create an NSKeyedUnarchiver by
calling alloc and initForReadingWithData : passing in the data we just fetched from the file wrapper.
Finally we call decodeObjectForKey : against our unarchiver and pass in our global key name @"DATA"
that we used earlier in the writing section. This unarchived data is returned.
I have used the term lazily load multiple times and now is the time that it should all come together.
We will create two accessor methods. Once for CTData and one for CTMetadata .
#pragma mark - Property Accessors
-(CTData *)data {
if(_data == nil){
if(_fileWrapper != nil)
_data = [self decodeObjectFromWrapperWithKey:kDataKey];
 
Search WWH ::




Custom Search