採用:
@interface Recipe : NSObject<NSCoding>
埋め込む:
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:name_ forKey:@"name"];
[coder encodeObject:recipePicture_ forKey:@"recipePicture"];
[coder encodeObject:dateAdded_ forKey:@"dateAdded"];
[coder encodeObject:ingredients_ forKey:@"ingredients"];
}
// Decode an object from an archive
- (id)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self!=NULL)
{
name_ = [coder decodeObjectForKey:@"name"];
recipePicture_ = [coder decodeObjectForKey:@"recipePicture"];
dateAdded_ = [coder decodeObjectForKey:@"dateAdded"];
ingredients_ = [coder decodeObjectForKey:@"ingredients"];
}
return self;
}
今あなたのセーブで:
- (void) save:(NSString*)path recipe:(Recipe*)recipe
{
NSMutableData* data=[[NSMutableData alloc] init];
if (data)
{
NSKeyedArchiver* archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
if (archiver)
{
[archiver encodeInt:1 forKey:@"Version"];
[archiver encodeObject:recipe forKey:@"Recipe"];
[archiver finishEncoding];
[data writeToFile:path atomically:YES];
}
}
}
そして負荷で:
- (Recipe*) load:(NSString*)path
{
Recipe* ret=NULL;
NSData* data=[NSData dataWithContentsOfFile:path];
if (data)
{
NSKeyedUnarchiver* unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
if (unarchiver)
{
int version=[unarchiver decodeIntForKey:@"Version"];
if (version==1)
{
ret=(Recipe*)[unarchiver decodeObjectForKey:@"Recipe"];
}
[unarchiver finishDecoding];
}
}
return ret;
}