-(NSDictionary *) dictionary{
unsigned int outCount = 0;
objc_property_t *propertyList = class_copyPropertyList([self class], &outCount);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for(int i = 0; i < outCount; i++){
objc_property_t property = propertyList[i];
const char * propertyName = property_getName(property);
SEL getter = sel_registerName(propertyName);
if ([self respondsToSelector:getter]) {
NSString *type = [NSString stringWithUTF8String:property_getAttributes(property)];
NSLog(@"type:%@",type);
if ([type hasPrefix:@"Ti"]) {
int value = ((int(*)(id,SEL))objc_msgSend)(self,getter);
NSString *key = [NSString stringWithUTF8String:propertyName];
[dict setObject:[NSNumber numberWithInt:value] forKey:key];
NSLog(@"key:%@,value:%d",key,value);
}else{
id value=((id(*)(id,SEL))objc_msgSend)(self,getter);
if ([value isKindOfClass:[self class]] && value) {
value = [value dictionary];
}
if (value) {
NSString *key = [NSString stringWithUTF8String:propertyName];
[dict setObject:value forKey:key];
NSLog(@"key:%@,value:%@",key,value);
}
}
}
}
return dict;
}
本文介绍了一段Objective-C代码,该代码演示了如何通过遍历类的属性并将它们转换为字典的方式,实现对象状态的序列化。具体包括获取类的所有属性名称及其对应的getter方法,然后调用这些方法来收集属性值,并将值存储在一个NSMutableDictionary中。
1642

被折叠的 条评论
为什么被折叠?



