[NSNull length]: unrecognized selector sent to instance
我遇到這個問題是因為從后臺獲取到的數據有NSNULL族壳,然后又進行了dictionary objectForkey:操作
解決方法:可以對獲取到的數據進行判斷憔辫,如果是null的話轉為@""
付代碼
+(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;
}
}
//將NSDictionary中的Null類型的項目轉化成@""
+(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類型的項目轉化成@""
+(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類型的項目轉化成@""
+(NSString *)nullToString
{
return @"";
}