xcode 如何检查数组中的值是否为 NULL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10077324/
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 if value in array is not NULL?
提问by Richard Knop
So I am parsing a twitter timeline. There is a field called "following" in the JSON response. It should be true or false.
所以我正在解析 Twitter 时间线。JSON 响应中有一个名为“following”的字段。它应该是真的或假的。
But sometimes the field is missing.
但有时该字段会丢失。
When I do:
当我做:
NSLog(@"%@", [[[timeline objectAtIndex:i] objectForKey:@"user"] objectForKey:@"following"]);
This is the output:
这是输出:
1
1
0
0
1
<null>
1
1
So how to check for those values?
那么如何检查这些值呢?
回答by Louis
NSArray
and other collections can't take nil
as a value, since nil is the "sentinel value" for when the collection ends. You can find if an object is null by using:
NSArray
和其他集合不能nil
作为值,因为 nil 是集合结束时的“哨兵值”。您可以使用以下方法查找对象是否为空:
if (myObject == [NSNull null]) {
// do something because the object is null
}
回答by joerick
If the field is missing, NSDictionary -objectForKey: will return a nil pointer. You can test for a nil pointer like this:
如果该字段丢失, NSDictionary -objectForKey: 将返回一个 nil 指针。你可以像这样测试一个 nil 指针:
NSNumber *following = [[[timeline objectAtIndex:i] objectForKey:@"user"] objectForKey:@"following"];
if (following)
{
NSLog(@"%@", following);
}
else
{
// handle no following field
NSLog(@"No following field");
}
回答by Lee Fastenau
It's not the timeline element that's null. It's either the "user" dictionary or the "following" object that's null. I recommend creating a user model class to encapsulate some of the json/dictionary messiness. In fact, I bet you could find an open source Twitter API for iOS.
不是时间轴元素为空。它是“用户”字典或为空的“以下”对象。我建议创建一个用户模型类来封装一些 json/dictionary 的混乱。事实上,我敢打赌你可以找到一个适用于 iOS 的开源 Twitter API。
Either way, your code would be more readable as something like:
无论哪种方式,您的代码都将更具可读性,例如:
TwitterResponse *response = [[TwitterResponse alloc] initWithDictionary:[timeline objectAtIndex:i]];
NSLog(@"%@", response.user.following);
TwitterResponse
above would implement a readonly property TwitterUser *user
which would in turn implement NSNumber *following
. Using NSNumber
because it would allow null values (empty strings in the JSON response).
TwitterResponse
上面将实现一个只读属性TwitterUser *user
,该属性将依次实现NSNumber *following
. 使用NSNumber
是因为它允许空值(JSON 响应中的空字符串)。
Hope this helps get you on the right track. Good luck!
希望这有助于让您走上正轨。祝你好运!
回答by Vineesh TP
for checking array contain null value use this code.
检查数组包含空值使用此代码。
if ([array objectAtIndex:0] == [NSNull null])
{
//do something
}
else
{
}