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 ?
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With