NSKeyedArchiver可以歸檔系統(tǒng)對(duì)象旧困,也可以歸檔自定義對(duì)象醇份,不過自定義對(duì)象要實(shí)現(xiàn)NSCoding協(xié)議:
-(void)encodeWithCoder:(NSCoder *)aCoder 進(jìn)行編碼
-(id)initWithCoder:(NSCoder *)aDecoder解碼返回一個(gè)對(duì)象
比如我們定義一個(gè)Person類
----------------Person.h
@interface Person :NSObject<NSCoding>
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *gender;
@property(nonatomic,copy)NSString *hobby;
@end
----------------Person.m
@implementation Person
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
NSLog(@"decode...");
[aCoder encodeObject:_name forKey:@"_name"];
[aCoder encodeObject:_gender forKey:@"_gender"];
[aCoder encodeObject:_hobby forKey:@"_hobby"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
NSLog(@"encode...");
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"_name"];
self.gender = [aDecoder decodeObjectForKey:@"_gender"];
self.hobby = [aDecoder decodeObjectForKey:@"_hobby"];
}
return self;
}
-(NSString *)description{
return [NSString stringWithFormat:@"name=%@,gender=%@,hobby=%@",_name,_gender,_hobby];
}
開始儲(chǔ)存:
Person *p = [[Person alloc] init];
p.name = @"koreadragon";
p.gender = @"male";
p.hobby = @"fishing";
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
path = [NSString stringWithFormat:@"%@/korea.info",NSTemporaryDirectory()];
BOOL archResult = [NSKeyedArchiver archiveRootObject:p toFile:path];
NSLog(@"%@",archResult ? @"儲(chǔ)存成功":@"儲(chǔ)存失敗");
解析:
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
NSLog(@"解檔出的文件:%@",p);