gpt4 book ai didi

ios - 将 NSDictionary 映射到 NSObject 子类

转载 作者:搜寻专家 更新时间:2023-10-30 20:18:55 24 4
gpt4 key购买 nike

我正在开发 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

这是正确/好的方法,还是我需要添加更多内容?

最佳答案

这是一种可行的方法。我发现 json 键很少是我对象属性最合适的名称,所以我见过的大多数人的代码都手动设置了他们对象的每个属性,这样他们就可以 1) 随意命名 2) 转换为原始值json 字典,它总是包含对象。 (例如 NSNumber -> float )

关于ios - 将 NSDictionary 映射到 NSObject 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18684083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com