自定义对象及存储自定义对象数组的持久化
2016-03-29 本文已影响504人
dididududididu
自定义对象
- 首先创建一个
Person
类,继承自NSObject
,需要遵守<NSCoding>
协议@interface Person : NSObject<NSCoding>
声明一个name属性@property(nonatomic,strong)NSString *name;
- 实现两个代理方法
//当对象进行归档操作的时候,会自动调用该方法
-(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];