xcode 如何检查xcode中返回的空对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18918611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to check for null object returned in xcode
提问by Bart
I have a NULL object returned from a JSON query string and I don't know how to check for it in an If statement. My syntax is below but I still don't seem to be able to trap for the NULL
class (i.e., if nothing is returned then no text variable can be set therefore it MUST be a NULL
class?), anyway, I need to check that the @"BillingStreet"
has something in it and if not to avoid processing it (else the app crashes as it tries to set nothing to the text value of one of the fields
in the VC
):
我有一个从 JSON 查询字符串返回的 NULL 对象,但我不知道如何在 If 语句中检查它。我的语法如下,但我似乎仍然无法捕获NULL
该类(即,如果没有返回任何内容,则无法设置文本变量,因此它必须是一个NULL
类?),无论如何,我需要检查@"BillingStreet"
在它的东西,如果不避免处理它(否则应用程序崩溃,因为它试图以一套没有什么的一个文本值fields
中VC
):
- (void) tableView: (UITableView *)itemTableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath{
NSDictionary *obj = [self.dataCustomerDetailRows objectAtIndex:indexPath.row];
NSString *text = [obj objectForKey:@"BillingStreet"] == nil ? @"0" : [obj objectForKey:@"BillingStreet"];
NSLog(@"%@",text);
if (text.class == NULL){
} else {
NSLog(@"no street");
self.labelCustomerAddress.text = [obj objectForKey:@"BillingStreet"];
}
}
回答by Martin R
A JSON "null" value is converted to [NSNull null]
, which you can check
for with
JSON“空”值转换为[NSNull null]
,您可以使用
if (text == [NSNull null]) ...
because it is a singleton.
因为它是单例。
Alternatively, you can check if the object contains the expected type, i.e. a string:
或者,您可以检查对象是否包含预期类型,即字符串:
NSString *text = [obj objectForKey:@"BillingStreet"];
if ([text isKindOfClass:[NSString class]]) {
self.labelCustomerAddress.text = text;
} else {
self.labelCustomerAddress.text = @"no street";
}
This is more robust in the case that a server sends bad data, e.g. a number or an array instead of a string.
在服务器发送错误数据(例如,数字或数组而不是字符串)的情况下,这更可靠。
回答by Ildar Sh
text == nil ? @"0" : text
text == nil ? @"0" : text
or
或者
text ? text : @"0"
text ? text : @"0"
But if you get it from JSON then you may get instance of NSNull
class. In this case you should check
但是如果你从 JSON 中得到它,那么你可能会得到NSNull
类的实例。在这种情况下,您应该检查
text && ![text isKindOfClass:[NSNull class]] ? text : @"0"
text && ![text isKindOfClass:[NSNull class]] ? text : @"0"