NSNull crashes my initWithDictionary

我的梦境 提交于 2019-12-02 07:53:50

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!