iOS runtime归档

2019-01-20  本文已影响0人  木_穆
- (void)encodeWithCoder:(NSCoder *)coder{
    //告诉系统归档的属性是哪些
    unsigned int count = 0;//表示对象的属性个数
    Ivar *ivars = class_copyIvarList([UserDataModel class], &count);
    for (int i = 0; i<count; i++) {
        //拿到Ivar
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);//获取到属性的C字符串名称
        NSString *key = [NSString stringWithUTF8String:name];//转成对应的OC名称
        //归档 -- 利用KVC
        [coder encodeObject:[self valueForKey:key] forKey:key];
    }
    free(ivars);//在OC中使用了Copy、Creat、New类型的函数,需要释放指针!!(注:ARC管不了C函数)
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super init];
    if (self) {
        //解档
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([UserDataModel class], &count);
        for (int i = 0; i<count; i++) {
            //拿到Ivar
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];
            //解档
            id value = [coder decodeObjectForKey:key];
            // 利用KVC赋值
            [self setValue:value forKey:key];
        }
        free(ivars);
    }
    return self;
}
- (IBAction)save:(UIButton *)sender {
    UserDataModel *person = [[UserDataModel alloc] init];
    //这里以temp路径为例,存到temp路径下
    NSString *temp = NSTemporaryDirectory();
    NSString *filePath = [temp stringByAppendingPathComponent:@"obj.data"]; //注:保存文件的扩展名可以任意取,不影响。
    NSLog(@"%@", filePath);
    //归档
    [NSKeyedArchiver archiveRootObject:person toFile:filePath];
}

- (IBAction)read:(UIButton *)sender {
    //取出归档的文件再解档
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"obj.data"];
    //解档
    UserDataModel *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
海到尽头天为岸
链接:https://www.jianshu.com/p/3e08fa21316d


上一篇下一篇

猜你喜欢

热点阅读