oc中的归档就是把对象写到文件中.
首先模型必须遵守NSCoding协议,并且实现其中的方法 (归档):- (void)encodeWithCoder:(NSCoder*)aCoder;(解档):- (id)initWithCoder:(NSCoder*)aDecoder;
@interfacePerson :NSObject<NSCoding>
@property(nonatomic,copy)NSString*name;//名称
@property(nonatomic,strong)NSNumber*age;//年龄
@property(nonatomic,copy)NSString*occupation;//职业
@property(nonatomic,copy)NSString*nationality;//国籍
@end
/**
*归档***编码
*
*@param aCoder
*/
- (void)encodeWithCoder:(NSCoder*)aCoder{
unsignedintcount =0;
Ivar*ivars =class_copyIvarList([selfclass], &count);
for(NSIntegeri=0; i
Ivarivar = ivars[i];
constchar*iName =ivar_getName(ivar);
NSString*iStr = [NSStringstringWithUTF8String:iName];
idvalue = [selfvalueForKey:iStr];
[aCoderencodeObject:valueforKey:iStr];
}
free(ivars);
}
//解码
- (id)initWithCoder:(NSCoder*)aDecoder{
self= [superinit];
if(self){
unsignedintcount =0;
Ivar*ivars =class_copyIvarList([selfclass], &count);
for(NSIntegeri=0; i
Ivarivar = ivars[i];
constchar*key =ivar_getName(ivar);
NSString*iName = [NSStringstringWithUTF8String:key];
idvalue = [aDecoderdecodeObjectForKey:iName];
[selfsetValue:valueforKey:iName];
}
free(ivars);
}
returnself;
}
Person*person = [[Personalloc]init];
person.name=@"xiaowei";
person.age=@(22);
person.occupation=@"IT程序猿";
person.nationality=@"中国";
NSString*path =NSHomeDirectory();
path = [pathstringByAppendingPathComponent:@"xiaowei"];
NSLog(@"paht = %@",path);
//归档
[NSKeyedArchiverarchiveRootObject:persontoFile:path];
//解归档
Person*laoxiao = [NSKeyedUnarchiverunarchiveObjectWithFile:path];
NSLog(@"欢迎%@岁的%@回到%@从事%@",laoxiao.age,laoxiao.name,laoxiao.occupation,laoxiao.nationality);