標籤: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 指標資料的問題