只有在类中实现的每个属性都都时量标(如int或float) 或都是遵循NSCoding协议的某个类的实例,就可以对整个对象进行完全归档
1.遵循NSCoding协议
--------------------
编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:foo forKey:kFooKey];
[aCoder encodeObject:bar forKey:kBarKey];
[aCoder encodeInt:someInt forKey:kSomeIntKey];
[aCoder encodeFloat:someFloat forKey:kSomeFloatKey];
}
如果要子类化某个也遵循NSCoding的类,还需要确保对超类调用encodeWithCoder:
[super encodeWithCoder:aCode];加在程序最开头
---------------------------解码
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
foo = [aDecoder decodeObjectForKey:kFooKey];
bar = [aDecoder decodeObjectForKey:kBarKey];
someInt = [aDecoder decodeIntForKey:kSomeIntKey];
someFloat = [aDecoder decodeFloatForKey:kSomeFloat];
}
}
当为某个具有超类且遵循NSCoding的类实现NSCoding时,不再调用super的init方法,而是调用initWithCoder:
if (self = [super initWithCoder:aDecoder])
2.实现NSCopying协议
- (id)copyWithZone:(NSZone *)zone
{
MyClass *copy = [[[self class] allocWithZone:zone]init];
copy.foo = [self.foo copyWithZone:zone];
copy.bar = [self.bar copyWithZone:zone];
copy.someInt = self.someInt;
copy.someFloat = self.someFloat;
return copy;
}
3.对数据对象进行归档和取消归档
归档
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:myObject forKey:@"keyValueString"];
[archiver finishEncoding];
BOOL success = [data writeToFile:@"/path/to/archive" atomically:YES];
写入文件错误success为NO
从归档重组对象步骤
NSData *data = [[NSData alloc] initWithContentsOfFile:@"/path/to/archive"];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self.object = [unarchiver decodeObjectForKey:@"keyValueString"];
[unarchiver finishDecoding];