有些后臺(tái)寫的不好葛闷,返回?cái)?shù)據(jù)的字段偶爾有NULL類型存在,如果不直接賦值給其他對(duì)象就會(huì)造成崩潰双藕。解決辦法的主要思路就是將其中的NULL對(duì)象轉(zhuǎn)換為@”“空字符串淑趾。以下是封裝好的方法創(chuàng)建一個(gè)字典的分類 .h文件#import@interface NSDictionary (SetNilStr)
+(id)changeType:(id)myObj;
@end
.m文件
#import "NSDictionary+SetNilStr.h"
@implementation NSDictionary (SetNilStr)
//將NSDictionary中的Null類型的項(xiàng)目轉(zhuǎn)化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
NSArray *keyArr = [myDic allKeys];
NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
for (int i = 0; i < keyArr.count; i ++)
{
id obj = [myDic objectForKey:keyArr[i]];
obj = [self changeType:obj];
[resDic setObject:obj forKey:keyArr[i]];
}
return resDic;
}
//將NSArray中的Null類型的項(xiàng)目轉(zhuǎn)化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
NSMutableArray *resArr = [[NSMutableArray alloc] init];
for (int i = 0; i < myArr.count; i ++)
{
id obj = myArr[i];
obj = [self changeType:obj];
[resArr addObject:obj];
}
return resArr;
}
//將NSString類型的原路返回
+(NSString *)stringToString:(NSString *)string
{
return string;
}
//將Null類型的項(xiàng)目轉(zhuǎn)化成@""
+(NSString *)nullToString
{
return @"";
}
//主要方法
//類型識(shí)別:將所有的NSNull類型轉(zhuǎn)化成@""
+(id)changeType:(id)myObj
{
if ([myObj isKindOfClass:[NSDictionary class]])
{
return [self nullDic:myObj];
}
else if([myObj isKindOfClass:[NSArray class]])
{
return [self nullArr:myObj];
}
else if([myObj isKindOfClass:[NSString class]])
{
return [self stringToString:myObj];
}
else if([myObj isKindOfClass:[NSNull class]])
{
return [self nullToString];
}
else
{
return myObj;
}
}
@end
需要轉(zhuǎn)換的時(shí)候調(diào)用以下方法就OK了,不管有多少個(gè)層級(jí)忧陪,全部轉(zhuǎn)換
//json表示獲取到的帶有NULL對(duì)象的json數(shù)據(jù)
NSDictionary *newDict = [NSDictionary changeType:json];