NSArray、NSDictionary、NSString 容错处理

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

NSArray

- (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

- (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

- (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 容错处理)