序列化和反序列化

//KeyArchiverTest序列化

//存储plist文件先找到要存储的path

NSString * filePath = [self filePath];

People * p = [[People alloc] init];

//存储数据的优先级按字节大小

p.name=@"序列化";

p.longName=@"序列化与反序列化";

p.age= 18;

//先对它进行序列化NSKeyedArchiver归档(转化为NSData) NSKeyedArchiver调用方法archivedDataWithRootObject

//1.BOOL类型的方法转化boolValue

//NSData * peopleData1 = [[NSKeyedArchiver archiveRootObject:p toFile:filePath]boolValue];

//2.NSKeyedArchiver

NSData* peopleData = [NSKeyedArchiver archivedDataWithRootObject:p];

//把二进制数写入本地

[peopleData writeToFile:filePath atomically:YES];

//NSLog(@"%@",peopleData);

//反序列化NSKeyedUnarchiver

//NSData * data = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

//首先要把二进制数据从文件中读取出来

NSData* data = [NSData dataWithContentsOfFile:filePath];

//对读取出来的二进制数进行反序列化

People *p1 = [NSKeyedUnarchiver unarchiveObjectWithData:data];

NSLog(@"%@",p1.longName);

NSLog(@"%@",p1.name);

NSString* str = [[NSString alloc] initWithData:people Dataencoding:NSUTF8StringEncoding];

NSLog(@"%@",str);//null

}

- (NSString *)filePath {

//获得沙盒根目录

NSString * hamePath =NSHomeDirectory();

//拼接文件路径

NSString * filePath = [hamePathstringByAppendingString:@"/Documents/arra.plist"];

//返回类型

NSLog(@"%@",filePath);

return filePath;

}

你可能感兴趣的:(序列化和反序列化)