归档 存储数据

归档一般都是保存自定义对象的时候,使用归档.因为plist文件不能够保存自定义对象.

如果一个字段当中保存有自定义对象,如果把这个字典写入到文件当中 它是不会生成Plist文件的


Person*persion = [[Person alloc]init];

person.name=@"WK";

person.age=18;

获取沙盒临时目录

NSString *tempPth = NSTemporaryDirectory();

NSString *filePath = [tempPath stringByAppendingPathComponent :@"person.data"];


[NSKeyedArchiver archivRootObject:person toFile:filePath];

archiveRootObject 这个方法底层会去调用保存对象的encodeWithCoder方法,去询问要保存这个对象的那些属性.

所以要实现encodeWithCoder方法 ,告诉要保存对象的那些属性.

需要遵循<NSCoding>协议

@interfacePersion :NSObject <NSCoding>

@property (nonatomic, strong)NSString *name; 

@property (nonatomic, assign) int age;

遵循协议后可以实现方法

需要报保存对象的属性

- (void)encodeWithCoder:(NSCoder *) encode{

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

[encode encodeInt32:self.age forKey:@"age"];

}

获取沙盒临时目录

NSString *tempPath =NSTemporaryDirectory();

NSString *filePath = [tempPath stringByAppendingPathComponent:@"persion.data"];


Persion *persion = [NSKeyedUnarchiver

unarchiveObjectWithFile:filePath];

NSKeyedUnarchiver 会调用initWithCoder来让你告诉他获取对象的那些属性

所以我们要在保存的对象中实现initWithCoder方法

initWithCoder会在解析文件的时候调用

-(instancetype)initWithCoder:(NSCoder*)decoder{

//因为遵循了NSCoding协议 所以不需要[super initWithCoder];

if  (self = [super init]) {

self.age = [decoder decodeInt32ForKey:@"age"];

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

//需要给里面的属性赋值,外界取得对象时访问该属性,里面才会有值  

}

return self;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容