对自定义类型的对象进行本地化保存,那么该类型必须实现NSCoding协议!
NSCoding 协议中只有两个方法,都是require的方法,一个是把本身的类型进行编码,一个是解码成类对象,返回一个对象。
-(void)encodeWithCoder:(NSCoder*)encoder
-(id)initWithCoder:(NSCoder *)decoder
NSKeyedArchiver是一个带键的归档器,可以将一个id对象序列化到文件中,常用于归档自定义类型对象;
常用方法:
+(BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
自定义的类 要实现
.h
@interface Grade : NSObject<NSCoding>
.m
#pragma mark - 在归档时自动调用的编码方法
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.userName forKey:@"UserName"];
[aCoder encodeInt:self.score forKey:@"Score"];
}
#pragma mark - 在归档时自动调用的编码方法
-(id)initWithCoder:(NSCoder *)aDecoder
{
self=[super init];
if(self){
self.userName=[aDecoder decodeObjectForKey:@"UserName"];;
self.score=[aDecoder decodeIntForKey:@"Score"];
}
return self;
}
解归档
NSKeyedUnarchiver 反序列化
+(id)unarchiveObjectWithFile:(NSString *)path;
Grade *g1=[[Grade alloc]initWithUserName:@"xiaowang" andScore:100];
Grade *g2 = [[Grade alloc]initWithUserName:@"xiaoli" andScore:200];
Grade *g3=[[Grade alloc]initWithUserName:@"zhangsan" andScore:210];
NSMutableArray *rankList=[NSMutableArray array];
[rankList addObject:g1];
[rankList addObject:g2];
[rankList addObject:g3];
// 序列化
BOOL flag=[NSKeyedArchiver archiveRootObject:rankList toFile:@"rankList.plist"];
// 反序列化
NSMutableArray *readRandkList=[NSKeyedUnarchiver unarchiveObjectWithFile:@"rankList.plist"];