iOS开发中经常会遇到空指针的问题。如从后台传回来的Json数据,程序中不做判断就直接赋值操作,很有可能出现崩溃闪退。为了解决空指针的问题,治标的方法就是遇到一个处理一个。这样业务代码里面就插了很多判断语句,费时又费力。现在有一个简单的办法。
利用AFNetworking网络请求框架获取数据。
1 2 3 4 5 6 7 |
AFHTTPRequestOperationManager *instance = [AFHTTPRequestOperationManager manager]; AFJSONResponseSerializer *response = (AFJSONResponseSerializer *)instance.responseSerializer; //添加这一句,移除所有的空值对象 response.removesKeysWithNullValues = YES; response.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/html", nil]; |
这样就可以删除掉含有null指针的key-value。
但有时候,我们想保留key,以便查看返回的字段有哪些。没关系,我们进入到这个框架的AFURLResponseSerialization.m类里,利用搜索功能定位到AFJSONObjectByRemovingKeysWithNullValues,改造如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { if ([JSONObject isKindOfClass:[NSArray class]]) { NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; for (id value in (NSArray *)JSONObject) { [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; } return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) { id value = (NSDictionary *)JSONObject[key]; if (!value || [value isEqual:[NSNull null]]) { //这里原本是这样写的 //[mutableDictionary removeObjectForKey:key]; //下面的是我们改动的 mutableDictionary[key] = @""; } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); } } return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; } return JSONObject; } |
转载请注明:怼码人生 » iOS空指针数据导致app闪退的解决