Database Reference
In-Depth Information
Inside our implementation we need to first implement the writing method for
UIDocument
, which is
contentsForType:error:
. To do this we will add a second method called
encodeObject:toWrappers:
withFilename:
#pragma mark - Document Writing Methods
- (id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
if(self.metadata == nil || self.data == nil)
return nil;
NSMutableDictionary *wrappers = [NSMutableDictionary dictionary];
[self encodeObject:_data toWrappers:wrappers withKey:kDataKey];
[self encodeObject:_metadata toWrappers:wrappers withKey:kMetadataKey];
NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:wrappers];
return fileWrapper;
}
- (void)encodeObject:(id<NSCoding>)object toWrappers:(NSMutableDictionary *)wrappers
withKey:(NSString *)key {
@autoreleasepool {
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:object forKey:@"DATA"];
[archiver finishEncoding];
NSFileWrapper *wrapper = [[NSFileWrapper alloc] initRegularFileWithContents:data];
[wrappers setObject:wrapper forKey:key];
}
}
Let's talk about
encodeObject:toWrappers:withFilename:
first. This method is passed three parameters.
The first is our object that conforms to the
NSCoding
protocol, which is going to be
NSData
or
NSMetadata
.
The second parameter is an
NSMutableDictionary
that we use to hold each
NSFileWrapper
that
contains the encoded data. The final parameter is the key used as the
NSFileWrapper
key for the
encoded object. We surround our actions in this method with an autoreleasepool so that the pool isn't
drained until we utilize the
NSMutableDictionary
in the calling method.
We start by creating an
NSMutableData
object called data. We then create an
NSKeyedArchiver
by
calling alloc and
initForWritingWithMutableData
: and passing our data object. We then call the
method
encodeObject:forKey
on the archiver. This takes our passed in object and encodes it. We
then wrap up the
NSKeyedArchiver
by calling
finishEncoding
.
The final step is to create an
NSFileWrapper
using alloc and
initRegularFileWithContents
: and
passing it our data object that has been encoded. Then we add our wrapper to the passed in
wrappers mutable dictionary using the key we passed into the object.
Looking at
contentsForType:error:
you can see that we first check to see if metadata or data are
empty. By calling
self.metadata
and
self.data
, we utilize an accessor method that we will create
later to be able to lazily load our data. If either of these is
nil
, then we return out of this method.
Search WWH ::
Custom Search