iOS数据持久化(三)-序列化

NSKeyedArchiver是NSCoder的具体子类,提供了一种方法来将对象(和标量值)编码成与体系结构无关的格式可以存储在一个文件中。NSKeyedArchiver可以存储的数据类型包括:NSString、NSArray、NSDictionary、NSData。

1、NSString归档与反归档

NSString *name = @"李四";

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

path = [path stringByAppendingString:@"string"];

self.filePath = path;

[NSKeyedArchiver archiveRootObject:name toFile:path];

解档

NSString *string1 = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];


2、NSArray归档与反归档

NSArray *Array = @[@"1",@"10",@"100"];

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

path = [path stringByAppendingString:@"Array"];

self.filePath = path;

[NSKeyedArchiver archiveRootObject:Array toFile:path];

解档

NSArray *array1 = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];


3、字典归档与反归档

NSDictionary *dict1 = @{@"name":@"潘凤",@"age":@"20"};

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

path = [path stringByAppendingString:@"dict"];

self.filePath = path;

[NSKeyedArchiver archiveRootObject:dict1 toFile:path];

解档

NSDictionary *dict1 = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];

NSLog(@"dict1-------%@",dict1);


4、自定义归档类型

自定义对象需要遵守NSCoding协议,实现下面2个方法

-(void)encodeWithCoder:(NSCoder *)aCoder

-(id)initWithCoder:(NSCoder *)aDecoder

1、读取实例变量,并把这些数据写到NSCoder中去,即序列化数据

-(void)encodeWithCoder:(NSCoder *)aCoder

{

[aCoder encodeObject:self.name forKey:@"name"];

[aCoder encodeObject:self.sex forKey:@"sex"];

[aCoder encodeInteger:self.age forKey:@"age"];

[aCoder encodeObject:self.address forKey:@"address"];

}


2、从NSCoder中读取数据,保存到相应变量中,即反序列化数据

-(id)initWithCoder:(NSCoder *)aDecoder

{

if (self = [super init]) {

self.name = [aDecoder decodeObjectForKey:@"name"];

self.sex = [aDecoder decodeObjectForKey:@"sex"];

self.age = [aDecoder decodeIntegerForKey:@"age"];

self.address = [aDecoder decodeObjectForKey:@"address"];

}

return self;

}

举例说明:

1、归档过程

JFModel *model = [[JFModel alloc]init];

model.name = @"张三";

model.sex = @"男";

model.age = 10;

model.address = @"北京";

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

path = [path stringByAppendingString:@"/model.plist"];

self.filePath = path;

NSLog(@"path------%@",path);

[NSKeyedArchiver archiveRootObject:model toFile:path];

2、反归档过程

JFModel *model1 = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];

NSLog(@"姓名:%@---性别:%@---年龄:%ld---住址:%@",model1.name,model1.sex,model1.age,model1.address);

你可能感兴趣的:(iOS数据持久化(三)-序列化)