NSArray、NSDictionary、NSString 容錯(cuò)處理

開發(fā)中常常因?yàn)榉?wù)端數(shù)據(jù)異常容易導(dǎo)致APP崩潰,以及程序數(shù)組字典字符串取值時(shí)容易崩潰的問題,我們需寫各自的分類來擴(kuò)展方法進(jìn)行容錯(cuò)處理

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;
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容