Problems with null pointers are often encountered in iOS development.
such as JSON data sent back from the background, the program does not infer the direct assignment operation, it is very likely that a crash flashback.
To solve the problem of NULL pointers, the workaround is to encounter a processing one. In this way, there is a lot of inference in the business code, which is time consuming and laborious.
Now there is an easy way.
Get the data using the Afnetworking Network request framework.
AFHTTPRequestOperationManager *instance = [AFHTTPRequestOperationManager manager];AFJSONResponseSerializer *response = (AFJSONResponseSerializer *)instance.responseSerializer;response.removesKeysWithNullValues = YES;response.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/html", nil];
This removes the key-value that contains the null pointer.
But sometimes we want to keep the key in order to see what fields are returned. It doesn't matter, we go into the AFURLRESPONSESERIALIZATION.M class of this framework, use the search function to locate the afjsonobjectbyremovingkeyswithnullvalues, post the code:
Static IDAfjsonobjectbyremovingkeyswithnullvalues (IDJsonobject, Nsjsonreadingoptions readingoptions) {if([Jsonobject iskindofclass:[NsarrayClass]]) {Nsmutablearray*mutablearray = [Nsmutablearrayarraywithcapacity:[(Nsarray*) Jsonobject Count]]; for(IDValue in (Nsarray*) jsonobject) {[Mutablearray addobject:afjsonobjectbyremovingkeyswithnullvalues (value, readingoptions)]; }return(Readingoptions & nsjsonreadingmutablecontainers)? Mutablearray: [NsarrayArraywitharray:mutablearray]; }Else if([Jsonobject iskindofclass:[nsdictionaryClass]]) {nsmutabledictionary*mutabledictionary = [nsmutabledictionaryDictionarywithdictionary:jsonobject]; for(ID<NSCopying> Key in [(nsdictionary*) Jsonobject AllKeys]) {IDValue = (nsdictionary*) Jsonobject[key];if(!value | | [Value isequal:[nsnull NULL]]) {//Here is the source of the author of the library //[mutabledictionary Removeobjectforkey:key]; //The following are modified. Change a null pointer type to an empty stringMutabledictionary[key] = @""; }Else if([Value iskindofclass:[NsarrayClass]] | | [Value iskindofclass:[nsdictionaryClass]]) {Mutabledictionary[key] = afjsonobjectbyremovingkeyswithnullvalues (value, readingoptions); } }return(Readingoptions & nsjsonreadingmutablecontainers)? Mutabledictionary: [nsdictionaryDictionarywithdictionary:mutabledictionary]; }returnJsonobject;}
Isn't it very easy, in a word, to change the null pointer value to an empty string.
Null pointer problem solved instantly, take to paste it.
Troubleshooting iOS NULL pointer data