关于ios “<null>”的异常处理

在iOS开发过程中经常需要与服务器进行数据通讯,但是在数据接通过程中会出现:null "<null>"等问题导致莫名其妙的崩溃。

相信你一定会写各种判断来处理这些异常,甚至你还会一个一个接口的去改,折让我们实在是心灰意冷。

再者可能你会写个分类 调它。这样也会让你非常的苦恼!

最近发现个处理的方法

如果你使用AFNetwork 这个库做网络请求的话,可以用以下代码,自动帮你去掉这个讨厌的空值:

self.removesKeysWithNullValues = YES;

这样就可以删除掉含有null指针的key-value。 
但有时候,我们想保留key,以便查看返回的字段有哪些。没关系,我们进入到这个框架的AFURLResponseSerialization.m类里,利用搜索功能定位到AFJSONObjectByRemovingKeysWithNullValues,贴出代码:

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;
}
将空指针value改为空字符串,空指针问题瞬间解决啦。


如果你没有用AF也没有关系下面我们来看看这个终极解决的办法:
终于找到了一劳永逸的方案,牛逼的老外写了一个Category,叫做NullSafe ,在运行时操作,把这个讨厌的空值置为nil,而nil是安全的,可以向nil对象发送任何message而不会奔溃。这个category使用起来非常方便,只要加入到了工程中就可以了,你其他的什么都不用做,对,就是这么简单。详细的请去Github上查看;
解压文件之后,直接将NullSafe.m文件导入到项目中就行了。

https://github.com/nicklockwood/NullSafe




原文地址:https://www.cnblogs.com/walkingzmz/p/6085762.html