- (void)encodeWithCoder:(NSCoder *)aCoder,和 - (instancetype)initWithCoder:(NSCoder *)aDecoder 这个两个方法,那如果有一个百个,一千个呢,是不是都要去自定义实现这两个方法。当然你也可以去这样做,我是比较懒的,我自己写了一个NSObject的类别,来实现所有的NSObject 子对象的归档,废话不多说,上代码
@implementation NSObject (KeyedArichiver)
- (void)encodeWithName:(NSString *)name{
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if(!name||name.length==0){
name = NSStringFromClass([self class]);
}
NSString *path =[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.arichiver",name]];
[NSKeyedArchiver archiveRootObject:self toFile:path];
}
+ (instancetype)decodeWithName:(NSString *)name{
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path =[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.arichiver",name]];
return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
unsigned int outCount;
Ivar *vars = class_copyIvarList([self class], &outCount);
for(int i=0;i<outCount;i++){
Ivar var = vars[i];
NSString *name = [NSString stringWithUTF8String:ivar_getName(var)];
id value = [self valueForKey:name];
[aCoder encodeObject:value forKey:name];
}
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [self init];
if(self){
unsigned int outCount;
Ivar *vars = class_copyIvarList([self class], &outCount);
for(int i=0;i<outCount;i++){
Ivar var = vars[i];
NSString *name = [NSString stringWithUTF8String:ivar_getName(var)];
id value = [aDecoder decodeObjectForKey:name];
[self setValue:value forKey:name];
}
}
return self;
}
@end