解決iOSnull 指標資料的問題

來源:互聯網
上載者:User

標籤:led   tty   network   nsset   資料   instance   track   add   操作   

iOS開發中常常會遇到null 指標的問題。

如從後台傳回來的Json資料,程式中不做推斷就直接賦值操作,非常有可能出現崩潰閃退。

為瞭解決null 指標的問題,治標的方法就是遇到一個處理一個。這樣業務代碼裡面就插了非常多推斷語句,費時又費力。

如今有一個簡單的辦法。


利用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];                //以下是修改後的。將null 指標類型改為空白字串                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,一句話,將null 指標value改為空白字串。

null 指標問題瞬間解決啦,拿去粘貼吧。

解決iOSnull 指標資料的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.