Person.h
1 #import <Foundation/Foundation.h> 2 3 @interface Person : NSObject <NSCoding> 4 5 /// 姓名 6 @property (nonatomic, copy) NSString *name; 7 8 /// 性别 9 @property (nonatomic, copy) NSString *gender; 10 11 /// 年龄 12 @property (nonatomic, assign) NSInteger age; 13 14 @end
Person.m
1 #import "Person.h" 2 3 @implementation Person 4 5 // 归档 6 // 将所有属性进行归档 7 - (void)encodeWithCoder:(NSCoder *)aCoder { 8 9 [aCoder encodeObject:self.name forKey:@"name"]; 10 [aCoder encodeObject:self.gender forKey:@"gender"]; 11 [aCoder encodeInteger:self.age forKey:@"age"]; 12 } 13 14 // 解档 15 - (instancetype)initWithCoder:(NSCoder *)aDecoder { 16 17 self = [super init]; 18 if (self) { 19 self.name = [aDecoder decodeObjectForKey:@"name"]; 20 self.gender = [aDecoder decodeObjectForKey:@"gender"]; 21 self.age = [aDecoder decodeIntegerForKey:@"age"]; 22 } 23 return self; 24 } 25 26 @end
ViewController.m
1 #import "ViewController.h" 2 #import "Person.h" 3 4 @interface ViewController () 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 13 // 如果把一个Person类型的对象存入本地,这个对象必须遵守NSCoding协议,实现协议中的两个方法 14 15 #pragma mark - 复杂对象的本地化 16 17 // 1.找到Documents文件夹的目录 18 NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 19 20 // 2.创建Person对象 21 Person *person = [[Person alloc] init]; 22 person.name = @"卫庄"; 23 person.gender = @"男"; 24 person.age = 18; 25 26 // 3.把这些复杂对象归档并存储 27 // 3.1 创建NSMutableData,用于初始化归档工具 28 NSMutableData *data = [NSMutableData data]; 29 // 3.2 创建归档工具 30 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 31 // 3.3 对需要归档的对象进行归档 32 [archiver encodeObject:person forKey:@"person"]; 33 // 3.4 结束归档 34 [archiver finishEncoding]; 35 // NSLog(@"%@", data); 36 37 // 4.将归档的内容NSMutableData存储到本地 38 NSString *personPath = [documentPath stringByAppendingPathComponent:@"person.plist"]; 39 [data writeToFile:personPath atomically:YES]; 40 NSLog(@"%@", personPath); 41 42 43 #pragma mark - 解档 44 45 // 1.将要解档的数据找出来 46 NSData *resultData = [NSData dataWithContentsOfFile:personPath]; 47 48 // 2.创建解档工具 49 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:resultData]; 50 51 // 3.对Person对象进行解档(要使用对象去接收) 52 Person *newPerson = [unarchiver decodeObjectForKey:@"person"]; 53 54 // 4.结束解档 55 [unarchiver finishDecoding]; 56 NSLog(@"name = %@, gender = %@, age = %ld", newPerson.name, newPerson.gender, newPerson.age); 57 58 } 59 60 @end
时间: 2024-10-12 12:48:45