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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:55:41  来源:igfitidea点击:

How to check if value in array is not NULL?

iphoneobjective-ciosxcode

提问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

NSArrayand other collections can't take nilas 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);

TwitterResponseabove would implement a readonly property TwitterUser *userwhich would in turn implement NSNumber *following. Using NSNumberbecause 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
{
}