一般客户端请求服务端数据,难免会遇到服务端某个字段为空的情况,这种情况下假如直接解析,就会得到一个nil对象。在用该数据赋值或者调用时候,很容易引起crash.假如每次用的时候进行安全判断,方法也可行。不过如果在源头上进行控制,可以减少因大意导致的crash。
可用如下递归方法,清除字典或数组里面的空对象,替换成我们定义的无数据的字段。
-(id)removeNillFromeDictOrArray:(id)object{
if ([object isKindOfClass:[NSNull class]]) {
return @"数据有误";
}else if([object isKindOfClass:[NSArray class]]){
NSMutableArray *temp_arr = [NSMutableArray arrayWithArray:object];
for (long i=0; i
id arr_objc = [temp_arr objectAtIndex:i];
if ([arr_objc isKindOfClass:[NSNull class]]) {
[temp_arr replaceObjectAtIndex:i withObject:@"数据有误"];
}else if([arr_objc isKindOfClass:[NSArray class]] || [arr_objc isKindOfClass:[NSDictionary class]]){
id temp_id = [self removeNillFromeDictOrArray:arr_objc];
[temp_arr replaceObjectAtIndex:i withObject:temp_id];
}
}
return temp_arr;
}else if([object isKindOfClass:[NSDictionary class]]){
NSMutableDictionary *temp_dict = [NSMutableDictionary dictionaryWithDictionary:object];
NSMutableArray *allKeys = [NSMutableArray arrayWithArray:[temp_dict allKeys]];
for (id key_temp in allKeys) {
id value_temp = [temp_dict valueForKey:key_temp];
if ([value_temp isKindOfClass:[NSNull class]]) {
[temp_dict setValue:@"数据有误" forKey:key_temp];
}else if([value_temp isKindOfClass:[NSArray class]] || [value_temp isKindOfClass:[NSDictionary class]]){
id temp_id = [self removeNillFromeDictOrArray:value_temp];
[temp_dict setValue:temp_id forKey:key_temp];
}
}
return temp_dict;
}else{
return object;
}
}