Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only iOS 7 crash [NSNull intValue]: unrecognized selector sent to instance

I want to get data from JSON service. Only iOS 7 version crash when get data from JSON value. It returns from JSON service below that:

{
    voteAverageRating = 0;
    voteCount = 0;
}

My code

int voteCount = [listDic objectForKey:@"voteCount"] intValue] ;

_LB_voteNumber.text = [NSString stringWithFormat:@"(%i)",voteCount];

Its work for iOS 5,5.1,6.0,6.1 but it crash only iOS7 version. It gave this error:

0x00098117 _mh_execute_header [NSNull intValue]: unrecognized selector sent to instance

Then i changed my code below that;

NSString *voteCount = [listDic objectForKey:@"voteCount"] ;

_LB_voteNumber.text = [NSString stringWithFormat:@"(%@)",voteCount];

When runs this code. It crashed again only iOS 7 version. It gave this error:

0x00098117 _mh_execute_header [NSNull length]: unrecognized selector sent to instance

How can i solve this problem ?

like image 544
SukruK Avatar asked Sep 19 '13 06:09

SukruK


2 Answers

Put a check before accessing the value from JSON like,

if([NSNull null] != [listDic objectForKey:@"voteCount"]) {
    NSString *voteCount = [listDic objectForKey:@"voteCount"];
    /// .... 
}

Reason for checking is, collection objects like NSDictionary do not allow values to be nil, hence they are stored as null. Passing intValue to a NSNull will not work as it will not recognise this selector.

Hope that helps!

like image 110
Amar Avatar answered Oct 05 '22 04:10

Amar


As the others have said, JSON null will be deserialized to NSNull. Unlike nil, You cannot send (most) messages to NSNull.

One solution is to add an implementation of -intValue on NSNull via category:

@implementation NSNull (IntValue)
-(int)intValue { return 0 ; }
@end

Now your code will work since sending -intValue to NSNull will now return 0

Another option: You could also add an "IfNullThenNil" category to NSObject...

@implementation NSObject (IfNullThenNil)
-(id)ifNullThenNil { return self ; }
@end

@implementation NSNull (IfNullThenNil)
-(id)ifNullThenNil { return nil ; }
@end

Now, your code becomes:

int voteCount = [[[listDic objectForKey:@"voteCount"] ifNullThenNil] intValue] ;

Just add a call to -ifNullThenNil wherever you access values from a JSON object.

like image 20
nielsbot Avatar answered Oct 05 '22 02:10

nielsbot