代码之家  ›  专栏  ›  技术社区  ›  Dan Ray

在不存在范围误差风险的情况下测试NSARRAY的内容

  •  4
  • Dan Ray  · 技术社区  · 14 年前

    我愚蠢地说:

    if ([imageCache objectAtIndex:index]) {
    

    问题是,在我第一次经历这个的时候,我没有把任何东西放进我的 NSMutableArray *imageCache ,这会发出一声“范围错误”。

    我怎样才能问一个非变异数组,它对于一个特定的索引是否有什么意义呢?

    6 回复  |  直到 13 年前
        1
  •  9
  •   Alex Reynolds    14 年前

    这个 NSArray 群集类无法存储 nil . 所以我认为只要检查边界就足够了:

    NSUInteger index = xyz; 
    if (index < [imageCache count]) { 
        id myObject = [imageCache objectAtIndex:index]; 
    }
    
        2
  •  7
  •   diederikh    13 年前

    我发现真正有用的是 safeObjectAtIndex: 方法。这将为您办理支票并返回 nil 如果索引超出范围。

    只需在NSarray上创建一个新类别,并包括以下方法:

    - (id)safeObjectAtIndex:(NSUInteger)index;
    {
        return ([self arrayContainsIndex:index] ? [self objectAtIndex:index] : nil);
    }
    
    - (BOOL)arrayContainsIndex:(NSUInteger)index;
    {
        return NSLocationInRange(index, NSMakeRange(0, [self count]));
    }
    
        3
  •  1
  •   Vladimir    14 年前
    if (index < [imageCache count])
       ...
    
        4
  •  1
  •   AlBeebe    13 年前

    此代码回答您的问题。与接受的答案不同,此代码处理传入负索引值。

    if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) {
        // Index does not exist
    } else {
        // Index exists
    }
    
        5
  •  0
  •   Andiih    14 年前

    [ImageCache Count]将返回数组中的项数。从那里拿过来:—)

        6
  •  0
  •   user342492    14 年前

    首先用[ImageCache Count]检查数组中的项数。不要试图要求任何索引大于该结果的内容。