iOS文件归档NSKeyedArchiver的使用

NSKeyedArchiver可以归档系统对象,也可以归档自定义对象,不过自定义对象要实现NSCoding协议:

-(void)encodeWithCoder:(NSCoder *)aCoder 进行编码

-(id)initWithCoder:(NSCoder *)aDecoder解码返回一个对象

比如我们定义一个Person类

----------------Person.h
@interface Person :NSObject

@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];
}

开始储存:

    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 ? @"储存成功":@"储存失败");

解析:

Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    NSLog(@"解档出的文件:%@",p);

你可能感兴趣的:(iOS文件归档NSKeyedArchiver的使用)