不少时候服务器传过来的空数据是NSNULL类型的,客户端没有作好判断,很容易形成程序崩溃。咱们能够将传过来的空数据用@""代替来解决问题。分别为字典和数组添加一个类目方法,将接收的字典或数组调用该方法便可。代码以下。数组
//字典 @interface NSDictionary (JRAdditions) - (NSDictionary *)dictionaryByReplacingNullsWithStrings; @end @implementation NSDictionary (JRAdditions) - (NSDictionary *)dictionaryByReplacingNullsWithStrings { const NSMutableDictionary *replaced = [self mutableCopy]; const id nul = [NSNull null]; const NSString *blank = @""; for (NSString *key in self) { id object = [self objectForKey:key]; if (object == nul) [replaced setObject:blank forKey:key]; else if ([object isKindOfClass:[NSDictionary class]]) [replaced setObject:[object dictionaryByReplacingNullsWithStrings] forKey:key]; else if ([object isKindOfClass:[NSArray class]]) [replaced setObject:[object arrayByReplacingNullsWithBlanks] forKey:key]; } return [NSDictionary dictionaryWithDictionary:[replaced copy]]; } @end //数组 @interface NSArray (NullReplacement) - (NSDictionary *)arrayByReplacingNullsWithBlanks; @end @implementation NSArray (NullReplacement) - (NSArray *)arrayByReplacingNullsWithBlanks { NSMutableArray *replaced = [self mutableCopy]; const id nul = [NSNull null]; const NSString *blank = @""; for (int idx = 0; idx < [replaced count]; idx++) { id object = [replaced objectAtIndex:idx]; if (object == nul) [replaced replaceObjectAtIndex:idx withObject:blank]; else if ([object isKindOfClass:[NSDictionary class]]) [replaced replaceObjectAtIndex:idx withObject:[object dictionaryByReplacingNullsWithStrings]]; else if ([object isKindOfClass:[NSArray class]]) [replaced replaceObjectAtIndex:idx withObject:[object arrayByReplacingNullsWithBlanks]]; } return [replaced copy]; } @end