在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