您的位置:首页 > 其它

用空字符串替换从服务器接收过来的NSNULL类型的数据

2013-11-22 16:04 113 查看
很多时候服务器传过来的空数据是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


本文出自 “破虏的冬天” 博客,请务必保留此出处http://chenpolu.blog.51cto.com/4292751/1330091
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: