Database Reference
In-Depth Information
#define kVersionKey @"VERSION"
#define kThumbnailKey @"THUMBNAIL"
#define kDisplayNameKey @"DISPLAY_NAME"
Now we will create two init methods. The first being our full init method, which assigns values to the
properties we created earlier on initialization and another that will call this method with nil values.
- (id)initWithThumbnail:(UIImage *)thumbnail andDisplayName:(NSString *)displayName{
if((self = [super init])){
_thumbnail = thumbnail;
_displayName = displayName;
}
return self;
}
- (id)init {
return [self initWithThumbnail:nil andDisplayName:nil];
}
The reason we have both these implementations is because when we create a document we won't
have any data, but if we are decoding a metadata object we will have data. If this is confusing,
the next methods should clear this up.
Now we need to implement our two NSCoding methods.
#pragma mark - NSCoding Methods
- (id)initWithCoder:(NSCoder *)aDecoder {
NSInteger version = [aDecoder decodeIntForKey:kVersionKey];
if(version == 1){
NSData *thumbnailData = [aDecoder decodeObjectForKey:kThumbnailKey];
UIImage *thumbnail = [UIImage imageWithData:thumbnailData];
NSString *displayName = [aDecoder decodeObjectForKey:kDisplayNameKey];
return [self initWithThumbnail:thumbnail andDisplayName:displayName];
} else {
return [self init];
}
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInt:1 forKey:kVersionKey];
NSData *thumbnailData = UIImagePNGRepresentation(_thumbnail);
[aCoder encodeObject:thumbnailData forKey:kThumbnailKey];
[aCoder encodeObject:_displayName forKey:kDisplayNameKey];
}
Let's start with the encodeWithCoder: method because it is the writing portion. This method gets
passed in an NSCoder object. We first use this object to encode and int value for the key kVersionKey .
The value we are encoding is 1 since this is our first version of the file. It is recommended that you
 
Search WWH ::




Custom Search