天天看点

归档和取档 (NSKeyedArchiver and NSKeyedUnarchiver)

iOS 归档和取档 (NSKeyedArchiver and NSKeyedUnarchiver)

定义Person类 ,用于存档和取档

Person类.h文件

// 归档和取档必须遵循NSCoding协议
@interface Person : NSObject <NSCoding>

// 定义属性
@property (nonatomic, strong)NSString *name;
@property (nonatomic, strong)NSString *age;
@property (nonatomic, strong)NSString *height;

//字典转模型方法
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)personWithDict:(NSDictionary *)dict;


@end
           

Person类.m文件

@implementation Person

// 字典转模型构造方法
- (instancetype)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

// 字典转模型便利构造方法
+ (instancetype)personWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}



// 归档必须执行的方法
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.age forKey:@"age"];
    [aCoder encodeObject:self.height forKey:@"height"];
}


// 取档必须执行的方法
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeObjectForKey:@"age"];
        _height = [aDecoder decodeObjectForKey:@"height"];
    }
    return self;
}

@end
           

main 函数代码

NSDictionary *dict = @{@"name":@"apple",@"age":@"23",@"height":@"167"};
    
    Person *person = [Person personWithDict:dict];
    NSLog(@"person = %@,%@,%@",person.name,person.age,person.height);
    
    
    // 文件路径
    NSString *str = @"/Users/Desktop/archiver";
    
    // 归档
    [NSKeyedArchiver archiveRootObject:person toFile:str];
    
    // 取档
    Person *person2 = [NSKeyedUnarchiver unarchiveObjectWithFile:str];
    NSLog(@"person2 = %@,%@,%@",person2.name,person2.age,person2.height);

    /*打印结果
      person = apple,23,167
      person2 = apple,23,167
     */