我正在研究cline-server应用程序。我从服务器获取JSON对象作为响应, 然后我将JSON转换为NSDictionary。现在我需要将NSDictionary映射到自定义数据对象。 所以我创建了BasicDataObject类:
#pragma mark - Inits
- (id)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
[self setValuesForKeysWithDictionary:dictionary];
}
return self;
}
#pragma mark - Service
- (id)valueForUndefinedKey:(NSString *)key {
NSArray *allKeys = [self allKeys];
id returnObject = nil;
BOOL keyFound = NO;
for (NSString *propertyName in allKeys) {
if ([propertyName isEqualToString:key]) {
id object = [self performSelector:NSSelectorFromString(key)];
returnObject = object ? object : [NSNull null];
keyFound = YES;
break;
}
}
if (!keyFound) {
@throw [NSException exceptionWithName:NSUndefinedKeyException reason:[NSString stringWithFormat:@"key '%@' not found", key] userInfo:nil];
}
return returnObject;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSString *capitalizedString = [key stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[key substringToIndex:1] capitalizedString]];
NSString *setterString = [NSString stringWithFormat:@"set%@:", capitalizedString];
[self performSelector:NSSelectorFromString(setterString) withObject:value];
}
- (void)setNilValueForKey:(NSString *)key {
object_setInstanceVariable(self, key.UTF8String, 0);
}
- (NSArray *)allKeys {
unsigned int propertyCount = 0;
objc_property_t *properties = class_copyPropertyList(self.class, &propertyCount);
NSMutableArray *propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char *name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
return propertyNames;
}
每个数据对象都是此类的子类,因此可以从NSDictionary初始化它。 如果某个数据对象子类需要一些自定义初始化,那么我将覆盖它:
- (id)initWithDictionary:(NSDictionary *)dictionary
这是正确/好的方法,还是我需要添加更多东西?
答案 0 :(得分:2)
这是一种可行的方法。我发现json键很少是我对象属性的最合适的名称,所以我手工看到的大多数人的代码都会在对象上设置每个属性,这样他们就可以1)将它命名为2)转换为原始值json字典,它总是包含对象。 (例如NSNumber - &gt;浮动)