NSArray、NSDictionary、NSString 容错处理

开发中常常因为服务端数据异常容易导致APP崩溃,以及程序数组字典字符串取值时容易崩溃的问题,我们需写各自的分类来扩展方法进行容错处理

NSArray

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (id)safeObjectAtIndex:(NSUInteger)index {
if (index < self.count) {
id object = self[index];
if (object == [NSNull null]) {
return nil;
}
return object;
}
return nil;
}

- (void)safeAddObject:(id)object{
if (object) {
[self addObject:object];
}
}

NSDictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (id)safeObjectForKey:(id)aKey
{
id object = [self objectForKey:aKey];
if (object == [NSNull null]) {
return nil;
}
return object;
}

- (void)safeSetObject:(id)anObject forKey:(id)aKey{
if(!aKey) {
return;
}
if(anObject) {
[self setObject:anObject forKey:aKey];
}
}

- (void)safeRemoveObjectForKey:(id)aKey {
if(aKey) {
[self removeObjectForKey:aKey];
}
}

NSString

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- (NSString *)safeCharacterAtIndex:(NSUInteger)index {
if (index < self.length) {
return [NSString stringWithFormat:@"%C",[self characterAtIndex:index]];
}else {
return nil;
}
}

- (NSString *)safeSubstringFromIndex:(NSUInteger)from {
if (from < self.length) {
return [self substringFromIndex:from];
}else {
return nil;
}
}

- (NSString *)safeSubstringToIndex:(NSUInteger)to {
if (to < self.length) {
return [self substringToIndex:to];
}else {
return nil;
}
}

- (NSString *)safeSubstringWithRange:(NSRange)range {
if (range.location < self.length && range.location + range.length < self.length) {
return [self substringWithRange:range];
}else {
return nil;
}
}

NSArray、NSDictionary、NSString 容错处理
http://example.com/2016/06/30/NSArray、NSDictionary、NSString-容错处理/
作者
guanzhendong
发布于
2016年6月30日
许可协议