hafedh
hafedh

Reputation: 539

xcode check if an NSArray exist and contains objects?

I'm trying to get some app info using Apple API, that gives me an JSON file containing many objects.

I tried to determine the type of the app (Universal/iPhone only/iPad only) like this

if(([[appDetails objectForKey:@"screenshotUrls"] count]>0) && ([[appDetails objectForKey:@"ipadScreenshotUrls"] count]>0))
{
    cell.appDeviceLabel.text = @"Universal";
    cell.appDeviceLabel.backgroundColor = [UIColor colorWithRed:0.012 green:0.467 blue:0.784 alpha:1];
}

else if(([[appDetails objectForKey:@"screenshotUrls"] count]==0) && ([[appDetails objectForKey:@"ipadScreenshotUrls"] count]>0)) 
{
    cell.appDeviceLabel.text = @"iPad";
    cell.appDeviceLabel.backgroundColor = [UIColor colorWithRed:0.941 green:0.58 blue:0.016 alpha:1];        
}          
else if(([[appDetails objectForKey:@"screenshotUrls"] count]>0) && ([[appDetails objectForKey:@"ipadScreenshotUrls"] count]==0))
{
    cell.appDeviceLabel.text = @"iPhone";
    cell.appDeviceLabel.backgroundColor = [UIColor colorWithRed:0.016 green:0.459 blue:0.129 alpha:1];
}

Note : screenshotUrls is an array containing the images for the iphone version ipadScreenshotUrls is the one for iPad photos.

I used the code above in my app and Apple accept it, but I get crash reports showing a problem at these lines.

May be because I'm testing the count of an array that is not found? because if the app is iphone only for exemple, the array for iPad images won't exist. Any idea how can I solve this ?

Thanks.

Upvotes: 0

Views: 1612

Answers (1)

Sailesh
Sailesh

Reputation: 26197

Does the JSON contains the value null for some key?

If yes, this value is converted to NSNull in Obj-C and any method passed to this objects results in a crash. (NSNull is different from nil in this respect.)

I usually encounter crashes with JSON in Obj-C for this reason very frequently. You should put a check in place before using any value.

if (value == (typecast)[NSNull null]) {
    // use the value
}

Note that type casting is done only to avoid compiler warning.

Upvotes: 2

Related Questions