自定义对象及存储自定义对象数组的持久化

2016-03-29  本文已影响504人  dididududididu
自定义对象
//当对象进行归档操作的时候,会自动调用该方法
 -(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
}```

//当对象进行反归档的时候调用
-(instancetype)initWithCoder:(NSCoder *)aDecoder{`
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
}return self;
}```

//创建一个Person对象
Person *person = [[Person alloc] init];
    person.name = @"小花";
//路径
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *path = [documentPath stringByAppendingPathComponent:@"person.plist"];
//进行归档并存入
[NSKeyedArchiver archiveRootObject:person toFile:path];
//用一个Person对象接受反归档返回的对象
Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
存储自定义对象的数组

数组内存储的对象也需要遵守<NSCoding>协议实现两个代理方法,具体如上

//创建两个person对象
    Person *person1 = [[Person alloc] init];
    person1.name = @"huahua";
    Person *person2 = [[Person alloc] init];
    person2.name = @"peipei";
    //将两个person对象存入数组
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:person1,person2, nil];
    //获取路径
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *path = [documentPath stringByAppendingPathComponent:@"array.plist"];
//将数组进行归档并存入指定路径
    [NSKeyedArchiver archiveRootObject:array toFile:path];
//用一个数组接收反归档的数据
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
上一篇下一篇

猜你喜欢

热点阅读