Reputation: 83755
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?
Upvotes: 3
Views: 5489
Reputation: 7973
for checking array contain null value use this code.
if ([array objectAtIndex:0] == [NSNull null])
{
//do something
}
else
{
}
Upvotes: -1
Reputation: 444
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!
Upvotes: -1
Reputation: 3634
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
}
Upvotes: 13
Reputation: 16468
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");
}
Upvotes: 3