How can I check if a value in an array is NULL?
So, I parse the timeline. The JSON response has a "follow" field. It must be true or false.
But sometimes this field is missing.
When I do this:
NSLog(@"%@", [[[timeline objectAtIndex:i] objectForKey:@"user"] objectForKey:@"following"]);
This is the conclusion:
1
1
0
0
1
<null>
1
1
So how do you check these values?
source to share
If the field is not present, NSDictionary -objectForKey: will return a null pointer. You can check for null 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");
}
source to share
It is not a timeline item that is null. It is either a "user" dictionary or a "next" object that is null. I recommend creating a user model class to encapsulate the json / dictionary messiness part. In fact, I'm sure you can find the open source Twitter API for iOS.
Either way, your code will be more readable, like something like:
TwitterResponse *response = [[TwitterResponse alloc] initWithDictionary:[timeline objectAtIndex:i]];
NSLog(@"%@", response.user.following);
TwitterResponse
above will implement the readonly property TwitterUser *user
, which in turn implements NSNumber *following
. Using NSNumber
because it would allow null values (empty strings in the JSON response).
Hope this helps you on the right track. Good luck!
source to share