天天看點

歸檔和取檔 (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
     */