views:

252

answers:

2

I am parsing a JSON file.

After getting the NSDictionary, I parse the objects in the dictionary into an array of objects. However, for certain JSON files, I get NULL, which should be fine, but it crashes my app for those place where I am expecting something but getting null:

- (id)initWithDictionary:(NSDictionary *)boxDictionary {
 if ([self init]) {
  // ... 
  int numberOfBoxes = [[boxDictionary valueForKey:@"box_count"] intValue];
  int numberOfItemsInBoxes = [[boxDictionary valueForKey:@"box_items_count"] intValue];
        // ..
 }
 return self;
}
+1  A: 

The basic problem seems to be that there is no intValue method on the NSNull that you're getting back from the call to valueForKey:.

You could add the intValue method, but what would you have it return for an NSNull? 0? -1?

The code to do that would look something like this.

In MyNullExtensions.h:

@interface NSNull (integer)
-(int) intValue;
@end

And in MyNullExtensions.m:

#import "MyNullExtensions.h"

@implementation NSNull (functional)
-(int) intValue
{
    return -1;
}
@end

Later, Blake.

bwinton
Thanks. Worked! You're smart, someone like Google or Mozilla should hire you.
Canada Dev
A: 

An int cannot be nil, so intValue doesn't have any way to tell you it can't get the intValue of a nil object. You need to check wether you got an object returned from valueForKey: before you ask for its intValue.

if ([boxDictionary valueForKey:@"box_count"])
    numberOfBoxes = [[boxDictionary valueForKey:@"box_count"] intValue];
Johan Kool