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

前端 未结 4 1229
情话喂你
情话喂你 2021-02-03 11:45

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 =         


        
4条回答
  •  梦谈多话
    2021-02-03 12:22

    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.

提交回复
热议问题