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?

+3


source to share


4 answers


NSArray

and other collections cannot accept nil

as a value, since nil is the "sentinel value" when the collection ends. You can find out if an object is null using:



if (myObject == [NSNull null]) {
    // do something because the object is null
}

      

+13


source


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");
}

      

+3


source


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!

-1


source


to test an array containing a null value, use this code.

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

      

-1


source







All Articles