NSNull crashes my initWithDictionary
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;
}
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.
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];
Just do a simple test against NSNull before you call intValue. No need to extend NSNull object.
if ([rate valueForKey:@"value"]!=[NSNull alloc]) {
// put your code here
}
精彩评论