开发者

NSNull crashes my initWithDictionary

开发者 https://www.devze.com 2022-12-12 22:07 出处:网络
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 cra

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消