iOS自動化歸檔

- (void)encodeWithCoder:(NSCoder *)encoder {
    //  利用runtime獲取實例變量的列表
    [self encodeWithClass:[self class] coder:encoder];
}

- (void)encodeWithClass:(Class)class coder:(NSCoder *)encoder {
    NSString *class_string = NSStringFromClass(class);
    if (![class_string isEqualToString:@"NSObject"]) {
        id obj = [class new];
        [self encodeWithClass:[obj superclass] coder:encoder];
    } else {
        return;
    }
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList(class, &count);
    for (int i = 0; i < count; i ++) {
        //  取出i位置對應的實例變量
        Ivar ivar = ivars[i];
        //  查看實例變量的名字
        const char *name = ivar_getName(ivar);
        //  C語言字符串轉化爲NSString
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        //  利用KVC取出屬性對應的值
        id value = [self valueForKey:nameStr];
        //  歸檔
        [encoder encodeObject:value forKey:nameStr];
    }
    //  記住C語言中copy出來的要進行釋放
    free(ivars);
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        [self deCoderWithClass:[self class] coder:decoder];
    }
    return self;
}

- (void)deCoderWithClass:(Class)class coder:(NSCoder *)decoder {
    NSString *class_string = NSStringFromClass(class);
    if (![class_string isEqualToString:@"NSObject"]) {
        id obj = [class new];
        [self deCoderWithClass:[obj superclass] coder:decoder];
    } else return;
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList(class, &count);
    for (int i = 0; i < count; i ++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        //
        NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        id value = [decoder decodeObjectForKey:key];
        //  設置到成員變量身上
        [self setValue:value forKey:key];
    }
    free(ivars);
}
參考:http://blog.csdn.net/oqingting12345/article/details/48929491
相關文章
相關標籤/搜索