1 #import "ViewController.h" 2 #import "Person.h" 3 @interface ViewController () 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 Person *p1 = [Person new]; 12 p1.name = @"Jackie Chan"; 13 p1.age = 16; 14 //将复杂对象转为NSData,归档(序列化) 15 NSData *p1Data = [NSKeyedArchiver archivedDataWithRootObject:p1]; 16 17 //创建路径,存储p1Data 18 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"person"]; 19 NSLog(@"%@",path); 20 [p1Data writeToFile:path atomically:YES]; 21 22 //读取文件中的数据 23 NSData *p2Data = [NSData dataWithContentsOfFile:path]; 24 Person *p2 = [NSKeyedUnarchiver unarchiveObjectWithData:p2Data]; 25 26 NSLog(@"%@,%ld",p2.name,p2.age); 27 p2.name = @"Bruce Lee"; 28 p2.age = 18; 29 30 //使用归档工具进行归档 31 NSMutableData *mdata = [[NSMutableData alloc] init]; 32 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mdata]; 33 //进行归档 34 [archiver encodeObject:p1 forKey:@"person1"]; 35 [archiver encodeObject:p2 forKey:@"person2"]; 36 //结束归档 37 [archiver finishEncoding]; 38 NSLog(@"%@",mdata); 39 //反归档 40 //反归档工具 41 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:mdata]; 42 //进行反归档 43 Person *p3 = [unarchiver decodeObjectForKey:@"person1"]; 44 Person *p4 = [unarchiver decodeObjectForKey:@"person2"]; 45 NSLog(@"%@ %ld",p3.name,p3.age); 46 NSLog(@"%@ %ld",p4.name,p4.age); 47 //结束反归档 48 [unarchiver finishDecoding]; 49 }
1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject<NSCoding> 4 @property(nonatomic,copy) NSString *name; 5 @property (nonatomic,assign) NSInteger age; 6 @end
1 #import "Person.h" 2 3 @implementation Person 4 //归档(序列化) 协议方法,将属性转为二进制数据 5 - (void)encodeWithCoder:(NSCoder *)aCoder 6 { 7 [aCoder encodeObject:self.name forKey:@"name"]; 8 [aCoder encodeInteger:self.age forKey:@"age"]; 9 } 10 //反归档(反序列化)方法,将二进制数据恢复为属性 11 - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder 12 { 13 self = [super init]; 14 if (self) { 15 self.name = [aDecoder decodeObjectForKey:@"name"]; 16 self.age = [aDecoder decodeIntegerForKey:@"age"]; 17 18 } 19 return self; 20 } 21 @end