您的位置:首页 > 其它

快速归档解档

2016-04-07 17:20 232 查看
创建一个BaseModel类,所有的对象都继承这个BaseModel就可以了。附上BaseModel代码

#import "BaseModel.h"

#import <objc/runtime.h>

@implementation BaseModel

- (id)initWithCoder:(NSCoder *)aDecoder{

if (self = [super
init]) {

Class c = self.class;

while (c && c != [NSObject
class]) {

unsigned
int count = 0;

Ivar *ivars =
class_copyIvarList(c, &count);

for (int i =
0; i < count; i++) {

NSString *key = [NSString
stringWithUTF8String:ivar_getName(ivars[i])];

id value = [aDecoder
decodeObjectForKey:key];

[self
setValue:value forKey:key];

}

c = [c superclass];

free(ivars);

}

}

return
self;

}

- (void)encodeWithCoder:(NSCoder *)aCoder{

Class c = self.class;

while (c && c != [NSObject
class]) {

unsigned int count =
0;

Ivar *ivars =
class_copyIvarList(c, &count);

for (int i =
0; i < count; i++) {

Ivar ivar = ivars[i];

NSString *key = [NSString
stringWithUTF8String:ivar_getName(ivar)];

id value = [self
valueForKey:key];

[aCoder encodeObject:value
forKey:key];

}

c = [c superclass];

free(ivars);

}

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: