您的位置:首页 > 移动开发 > Objective-C

NSObject + NSCoding Category

2015-12-31 19:32 501 查看
在.h文件中 <NSCoding>

在.m文件中

#import <objc/objc-runtime.h>

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

self = [self
init];

if (self) {

unsigned int count =
0;

objc_property_t *propertyList =
class_copyPropertyList([self
class], &count);

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

objc_property_t property = propertyList[i];

const
char *propertyName = property_getName(property);

//
将取出来的C语言字符串转化为OC字符串(char -> NSString)

NSString *propertyNameStr = [NSString
stringWithCString:propertyName
encoding:NSUTF8StringEncoding];

// 解档取出属性的值

id value = [aDecoder
decodeObjectForKey:propertyNameStr];

//
使用setValueForKey赋值,相当于set方法

[self
setValue:value forKey:propertyNameStr];

}

free(propertyList);

}

return
self;

}

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

unsigned int count =
0;

objc_property_t *propertyList =
class_copyPropertyList([self
class], &count);

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

objc_property_t property = propertyList[i];

const char *propertyName =
property_getName(property);

//
将取出来的C语言字符串转化为OC字符串(char -> NSString)

NSString *propertyNameStr = [NSString
stringWithCString:propertyName
encoding:NSUTF8StringEncoding];

//
取出当前属性的值,相当于self.name

id value = [self
valueForKey:propertyNameStr];

[aCoder encodeObject:value
forKey:propertyNameStr];

}

free(propertyList);

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