ObjectiveC对象序列化通用的NSCoder成员方法

 

创新互联联系热线:13518219792,为您提供成都网站建设网页设计及定制高端网站建设服务,创新互联网页制作领域10多年,包括成都VR全景等多个领域拥有丰富的营销推广经验,选择创新互联,为企业锦上添花。

/* NSCoder functions taken from:

 *http://davedelong.com/blog/2009/04/13/aspect-oriented-programming-objective-c

 */


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

if ([super respondsToSelector:@selector(initWithCoder:)] && ![self isKindOfClass:[super class]]) {

self = [super performSelector:@selector(initWithCoder:) withObject:decoder];

} else {

self = [super init];

}

if (self ==nil) {returnnil; }

    

NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc]init];

unsigned int numIvars = 0;

Ivar *ivars = class_copyIvarList([self class], &numIvars);

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

Ivar thisIvar = ivars[i];

NSString *key = [NSStringstringWithUTF8String:ivar_getName(thisIvar)];

id value = [decoder decodeObjectForKey:key];

if (value == nil) { value = [NSNumber numberWithFloat:0.0]; }

[self setValue:value forKey:key];

}

if (numIvars > 0) { free(ivars); }

[pool drain];

returnself;

}

 

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

if ([super respondsToSelector:@selector(encodeWithCoder:)] && ![self isKindOfClass:[super class]]) {

[super performSelector:@selector(encodeWithCoder:) withObject:encoder];

}

NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc]init];

unsigned int numIvars = 0;

Ivar *ivars = class_copyIvarList([self class], &numIvars);

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

Ivar thisIvar = ivars[i];

NSString *key = [NSStringstringWithUTF8String:ivar_getName(thisIvar)];

id value = [self valueForKey:key];

[encoder encodeObject:value forKey:key];

}

if (numIvars > 0) { free(ivars); }

[pool drain];

}

 

文章名称:ObjectiveC对象序列化通用的NSCoder成员方法
本文链接:http://azwzsj.com/article/pjgjhs.html