"等问题...">
美文网首页
关于ios “<null>”的异常处理

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

作者: MxlZlh | 来源:发表于2018-08-29 14:10 被阅读56次

    在iOS开发过程中需要与服务器进行数据通讯,但是问题来了,接口返回的数据中会出现:null "<null>"等问题,导致crash。

    让接口修改?好主意!但是。。。理想很美好现实很骨感!

    那就只能我们自己改了。

    要一个接口一个接口的去改?那就只能呵呵了。

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

    你可能需要看看下面的2种处理方法

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

    ((AFJSONResponseSerializer *)_httpSessionManager.responseSerializer).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

    image

    相关文章

      网友评论

          本文标题:关于ios “<null>”的异常处理

          本文链接:https://www.haomeiwen.com/subject/vjohwftx.html