zoukankan      html  css  js  c++  java
  • 解决iOS空指针数据的问题

    iOS开发中常常会遇到空指针的问题。

    如从后台传回来的Json数据,程序中不做推断就直接赋值操作,非常有可能出现崩溃闪退。

    为了解决空指针的问题,治标的方法就是遇到一个处理一个。这样业务代码里面就插了非常多推断语句,费时又费力。

    如今有一个简单的办法。


    利用AFNetworking网络请求框架获取数据。

    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,贴出代码:

    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;
    }

    是不是非常easy,一句话,将空指针value改为空字符串。

    空指针问题瞬间解决啦,拿去粘贴吧。

  • 相关阅读:
    how to singleton pattern !
    n6600 支持keepalive吗?
    6600的几个不可能的任务!
    Heyy.... i am back with 100 Apps for nokia 6600!
    http client chunked implement via sun
    Excel公司正式发售WinA&D 4.0
    快速开发rails、==常用插件==
    单独使用ActionMailer作为邮件发送器为迩的程序发送报告
    如何在win7上添加自动启动项
    gem install 报错或是太慢,gem install 本地安装
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6994348.html
Copyright © 2011-2022 走看看