NSNull crashes my initWithDictionary

前端 未结 3 623
忘掉有多难
忘掉有多难 2021-01-28 13:17

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, wh

相关标签:
3条回答
  • 2021-01-28 14:00

    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];
    
    0 讨论(0)
  • 2021-01-28 14:01

    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.

    0 讨论(0)
  • 2021-01-28 14:09

    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 讨论(0)
提交回复
热议问题