这里以Person类对象为例 先创建一个Person类
Person.h
@interface Person : NSObject<NSCoding>// 注意一定要遵循NSCoding协议
///姓名
@property (nonatomic, copy) NSString *name;
///性别
@property (nonatomic, copy) NSString *gender;
///年龄
@property (nonatomic, assign) NSInteger age;
@end
Person.m
@implementation Person
//归档
//将所有的属性归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.gender forKey:@"gender"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
//解档(反归档)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.gender = [aDecoder decodeObjectForKey:@"gender"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
@end
准备好以后进行具体操作:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//如何把一个person对象存入本地 即为复杂对象的本地化 这个对象必须遵守NSCoding协议 并实现协议中的两个方法
pragma mark - 复杂对象的本地化
//1.找寻Documents文件夹的目录
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//2. 创建person对象
Person *person = [[Person alloc] init];
person.name = @"MBBoy";
person.gender = @"男";
person.age = 18;
//3 把这个复杂对象归档
//3.1 创建NSMutableData 用于创建归档工具的
NSMutableData *data = [NSMutableData data];
//3.2 创建归档工具
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//3.3 对要归档的person对象进行归档
[archiver encodeObject:person forKey:@"person"];
//3.4 结束归档
[archiver finishEncoding];
//NSLog(@"==data = %@==",data);
//4 将归档的内容NSMutableData存储在本地
NSString *personPath = [documentPath stringByAppendingPathComponent:@"person.plist"];
[data writeToFile:personPath atomically:YES];
NSLog(@"%@", personPath);
pragma mark - 解档
//1 将要解档的数据找出
NSData *resultData = [NSData dataWithContentsOfFile:personPath];
//2 创建解档工具
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:resultData];
//3 对person对象进行解档
Person * newperson = [unarchiver decodeObjectForKey:@"person"];
//4 结束解档
[unarchiver finishDecoding];
NSLog(@"person = %@", newperson);
}
解档就相当于把数据从本地取出