我有可能包含对象的 JSON 响应。在我的模型对象中,我这样做:
_price3 = self.serverData[@"price3"];
我想做类似的东西:
_price3 = self.serverData[@"price3"] ? self.serverData[@"price3"] : @"0";
问题是,在这样的构造中,它总是会评估为真,因为我猜是一个对象。
为了防止在我的属性中出现,我想将 getter 修改为变量,以检查值是 nsnull 的位置,如果是,则返回类似 @"0"的内容。那可能吗?
最佳答案
我在每个应用程序中都使用这种方法。
-(NSString*)checkNullValidation:(NSString *)key {
NSString *returnValue;
if(key == (id)[NSNull null] || [key isEqual:[NSNull null]] || key == nil) {
returnValue = @"";
}
else {
returnValue = [NSString stringWithFormat:@"%@",key];
}
return returnValue;
}
因此,每当我解析数据时,我都会进行如下检查
例如。,
NSDictionary *dictionaryTest = @{@"MyFirstKey":nil, @"MySecondKey":@"AwesomeValue"};
NSString *firstValue = [self checkNullValidation:[dictionaryTest valueForKey:@"MyFirstKey"]]; // It will be @"" instead of nil
NSString *secondValue = [self checkNullValidation:[dictionaryTest valueForKey:@"MySecondKey"]]; // It will be @"AwesomeValue"
因此,您获得
nil
的可能性为 0%。或 NULL
并且应用程序不会崩溃。即使响应正文中不存在您的 key ,此操作也将起作用。如果您想在多个屏幕上使用它,请创建一个通用处理程序类并将其添加为类方法并使用它。我几乎在所有应用程序中都使用过,并且我的应用程序从未因此而崩溃
nil
和 NULL
问题。
关于ios - 修改 getter 以避免 NSNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41440004/