3

So I am parsing a twitter timeline. There is a field called "following" in the JSON response. It should be true or false.

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?

4 Answers 4

13

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:

if (myObject == [NSNull null]) {
    // do something because the object is null
}
Sign up to request clarification or add additional context in comments.

Comments

3

If the field is missing, NSDictionary -objectForKey: will return a nil pointer. You can test for a nil pointer like this:

NSNumber *following = [[[timeline objectAtIndex:i] objectForKey:@"user"] objectForKey:@"following"];

if (following)
{
    NSLog(@"%@", following);
}
else
{
    // handle no following field
    NSLog(@"No following field");
}

Comments

-1

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.

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).

Hope this helps get you on the right track. Good luck!

Comments

-1

for checking array contain null value use this code.

if ([array objectAtIndex:0] == [NSNull null])
{
//do something
}
else
{
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.