// // FYObject.m // // // Created by qiao.zhiguang on 15/5/5. // Copyright (c) 2015年 All rights reserved. // #import "FYObject.h" #import <objc/runtime.h> @implementation FYObject -(void)encodeWithCoder:(NSCoder *)encoder { unsigned int count = 0; Ivar * ivars = class_copyIvarList([self class], &count); for (int i = 0; i<count; i++) { // 取出i位置对应的成员变量 Ivar ivar = ivars[i]; // 查看成员变量 const char *name = ivar_getName(ivar); // 归档 NSString *key = [NSString stringWithUTF8String:name]; id value = [self valueForKey:key]; [encoder encodeObject:value forKey:key]; } free(ivars); } -(id)initWithCoder:(NSCoder *)decoder { if (self = [super init]) { unsigned int count = 0; Ivar *ivars = class_copyIvarList([self class], &count); for (int i = 0; i<count; i++) { // 取出i位置对应的成员变量 Ivar ivar = ivars[i]; // 查看成员变量 const char *name = ivar_getName(ivar); // 归档 NSString *key = [NSString stringWithUTF8String:name]; id value = [decoder decodeObjectForKey:key]; // 设置到成员变量身上 [self setValue:value forKey:key]; } free(ivars); } return self; } - (NSString *)description{ NSLog(@"%@ %s", [self class],__func__); NSMutableString * descriptionStr = [[NSMutableString alloc]init]; unsigned int count = 0; Ivar *ivars = class_copyIvarList([self class], &count); for (int i = 0; i<count; i++) { // 取出i位置对应的成员变量 Ivar ivar = ivars[i]; // 查看成员变量 const char *name = ivar_getName(ivar); // 归档 NSString *key = [NSString stringWithUTF8String:name]; id value = [self valueForKey:key]; // 设置到成员变量身上 [descriptionStr appendFormat:@"{%@:%@},",key,value]; } free(ivars); return descriptionStr; } @end
代码分享:
encodeWithCoder
大概逻辑,获取 当前类的 属性列表 以及 属性的 个数 count ,然后遍历 所有 变量 取得 变量名 和 变量值 最后 进行 encode
[encoder encodeObject:valueforKey:key];
initWithCoder
获取当前类的属性列表,然后遍历, 根据 变量名 decode出 对应属性的 值 ,最后
[selfsetValue:valueforKey:key];