我正在尝试将我自己的对象集合深度解析为 NSDictionary(用于 JSON)。
我有一个基础对象类,我的所有模型都扩展了它,而这个基础对象又扩展了 NSObject:
@interface BaseObj : NSObject <DICTMaker>
- (NSMutableDictionary *) toDICT;
@end
在该方法中,我使用 objc-runtime 来获取属性列表。任何可以引用 using 的属性,我都会[self valueForKey:]
将属性的名称和值插入到我的字典中。
但是,到目前为止我注意到的是NSNumber
s 和用户定义的类没有添加到字典中!我的解析器最有把握地识别它们,因为我让它把所有东西都吐到日志中;但[self valueForKey:]
返回nil
所有NSNumbers
和用户定义的对象。
- (NSMutableDictionary *)toDICT {
NSMutableDictionary *props = [NSMutableDictionary dictionary];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
// Both of these work, I promise:
NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
NSString *propertyType = [NSString stringWithUTF8String:getPropertyType(property)];
NSLog( @"%@ of Type: %@", propertyName, propertyType );
id propertyValue = [self valueForKey:propertyName];
if ( [ propertyValue respondsToSelector:@selector(toDICT:) ] )
[ props setObject:[propertyValue toDICT] forKey:propertyName ];
else if ( propertyValue )
[ props setObject:propertyValue forKey:propertyName ];
else
NSLog( @"Unable to get ref to: %@", propertyName );
}
free(properties);
return props;
}
这是我扔给创建者的示例对象:
@interface UserRegistrationLocation : BaseObj {
NSString *address, *street, *street_2, *city;
NSNumber *addr_state, *addr_zip;
}
@interface UserRegistrationContact : BaseObj {
NSString *first_name, *last_name;
NSString *p_phone_area, *p_phone_first_3, *p_phone_last_4;
NSString *s_phone_area, *s_phone_first_3, *s_phone_last_4;
}
@interface UserRegistration : BaseObj {
NSString *email, *password, *password_confirm;
NSNumber *referral;
UserRegistrationContact *primary, *secondary;
UserRegistrationLocation *address;
}
NSMutableDictionary *mydict = [myUserRegistration toDICT];
生成的字典仅包含 email、password 和 password_confirm 的条目:
[11012:f803] Unable to get ref to: referral
[11012:f803] Unable to get ref to: primary
[11012:f803] Unable to get ref to: secondary
[11012:f803] Unable to get ref to: address
[11012:f803] {"user":{"password":"haxme123","password_confirm":"haxme123","email":"my@email.com"}}
请提供任何帮助=}!