自定义字典的存储:对象序列化

2017-10-23  本文已影响2人  MichalWilson

IOS中的自定义字典在存储的时候,如果使用NSUserDefaults来存储会报错Attempt to set a non-property-list object as an NSUserDefaults,因此我们需要把字典封装成一个model类灾后在进行编码和解码的方式来进行存储.

_array = [[NSMutableArray alloc] init];

for (int a = 0; a < 5; a++) {

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

people.name = [NSString stringWithFormat:@"张%d",a];

people.age = a;

[_array addObject:people];

}

NSLog(@"%@",NSHomeDirectory());

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/array.plist"];

注意:在进行序列化和反序列化的时候,使用的方法要保持一致,加号方法都是用加号方法,减号方法的话都使用减号方法

下面是使用减号方法的代码

1.创建序列化的对象的时候,首先需要创建一个可变的data来储存数据

NSMutableData *data = [[NSMutableData alloc] init];

创建序列化对象

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

2.通过这个序列化的对象对_array进行编码

[archiver encodeObject:_array forKey:@"myArray"];

3. 完成编码

[archiver finishEncoding];

//等完成编码之后, 那么这个可变的data中就有了数据.

4. 把data写入文件了

[data writeToFile:path atomically:YES];

下面是对象的反序列化

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/array.plist"];

//第三种方式

//1. 创建反序列化的对象

NSData *data = [NSData dataWithContentsOfFile:path];

NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

//2. 进行反序列化

NSArray *arr = [unArchiver decodeObjectForKey:@"myArray"];

NSLog(@"arr = %@",arr);

//3. 反序列化完成

[unArchiver finishDecoding];

下面是具体的代码链接https://github.com/xuchaofei/saveData

上一篇 下一篇

猜你喜欢

热点阅读