我遇到了一些从JSON解析的空值问题。由于我在看到null类型时将实体与UILabel链接,因此它会使应用程序崩溃。有没有什么好方法在视图上显示空值而不是在每组链接上检查null?
由于
答案 0 :(得分:3)
班级NSNull适用于此类情况。它用于不允许值null
(0x0)的集合中(NSArray
,NSDictionary
等。)
它的用法类似于以下内容:
id myValue = // get value from collection
// method one (recommended, as you could have more than one instance of NSNull)
if ([myValue isKindOfClass:[NSNull class])
{
// null value
}
// method two, not recommended
if (myValue == [NSNull null])
{
// null value
}
答案 1 :(得分:2)
if (objectHoldingJsonValue == [NSNull null]) {
// you have a null value, move in other value
}
答案 2 :(得分:0)
如果你想避免遍历JSON对象中的集合,你可以对UILabel进行子类化并覆盖“text”属性的setter,验证对它的值为NULL(例如,使用Richard的方法) :
- (void) setText:(NSString *)textValue
{
if ([textValue isKindOfClass:[NSNull class]]) textValue = nil;
[super setText:textValue];
}
当然,采用这种方法会让您对应用中的任何其他情况持开放态度,此NULL值可能会导致您遇到麻烦,这就是为什么在数据模型的上下文中验证/清理可能是首选。
答案 3 :(得分:0)
从JSON字典中生根NULL的最简单方法。与NSDictionary一起使用,不一定是可变的:
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSNull class]]) [dictionary setValue:[NSString stringWithString:@""] forKey:key];
} ];