复杂对象的本地化(以Person为例)

时间:2023-03-08 17:08:55

Person.h

 #import <Foundation/Foundation.h>

 @interface Person : NSObject <NSCoding>

 /// 姓名
@property (nonatomic, copy) NSString *name; /// 性别
@property (nonatomic, copy) NSString *gender; /// 年龄
@property (nonatomic, assign) NSInteger age; @end

Person.m

 #import "Person.h"

 @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

ViewController.m

 #import "ViewController.h"
#import "Person.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // 如果把一个Person类型的对象存入本地,这个对象必须遵守NSCoding协议,实现协议中的两个方法 #pragma mark - 复杂对象的本地化 // 1.找到Documents文件夹的目录
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:]; // 2.创建Person对象
Person *person = [[Person alloc] init];
person.name = @"卫庄";
person.gender = @"男";
person.age = ; // 3.把这些复杂对象归档并存储
// 3.1 创建NSMutableData,用于初始化归档工具
NSMutableData *data = [NSMutableData data];
// 3.2 创建归档工具
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 3.3 对需要归档的对象进行归档
[archiver encodeObject:person forKey:@"person"];
// 3.4 结束归档
[archiver finishEncoding];
// NSLog(@"%@", 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(@"name = %@, gender = %@, age = %ld", newPerson.name, newPerson.gender, newPerson.age); } @end