Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 测试NSArray的内容而不冒范围错误的风险_Iphone_Objective C - Fatal编程技术网

Iphone 测试NSArray的内容而不冒范围错误的风险

Iphone 测试NSArray的内容而不冒范围错误的风险,iphone,objective-c,Iphone,Objective C,我愚蠢地说: if ([imageCache objectAtIndex:index]) { 问题是,在我第一次这样做时,我没有在我的NSMutableArray*imageCache中放入任何内容,这会导致范围错误 如何询问NSMutableArray是否有特定索引的内容?if(索引

我愚蠢地说:

if ([imageCache objectAtIndex:index]) {
问题是,在我第一次这样做时,我没有在我的
NSMutableArray*imageCache
中放入任何内容,这会导致范围错误

如何询问NSMutableArray是否有特定索引的内容?

if(索引<[imageCache count])
if (index < [imageCache count])
   ...
...
[imageCache count]将返回阵列中的项目数。从这里开始:-)

首先用[imageCache count]检查数组中的项目数。不要试图要求索引大于该结果的任何内容。
NSArray
群集类无法存储
nil
。因此,我认为只需检查边界就足够了:

NSUInteger index = xyz; 
if (index < [imageCache count]) { 
    id myObject = [imageCache objectAtIndex:index]; 
}
nsu整数索引=xyz;
如果(索引<[imageCache计数]){
id myObject=[imageCache objectAtIndex:index];
}

我发现真正有用的是有一个
安全对象索引:
方法。这将为您执行检查,如果索引超出范围,则返回
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]));
}

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

if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) {
    // Index does not exist
} else {
    // Index exists
}

好的,下一个相关的问题,这揭示了。。。我异步加载这些图像,它们的大小都不一样。所以没人知道他们会按什么顺序来找我。似乎当我尝试对一个不存在的索引执行
[imageCache insertObject:image atIndex:index]
时,我也会得到一个范围错误。NSArray必须是连续的吗?为什么不直接使用
NSMutableArray
方法
-addObject:
?我刚刚“解决”了这个问题,检查我的[计数]是否与我试图输入的索引一样深,并添加@“直到我这样做。(另外,我确实需要replaceObjectAtIndex:withObject而不是insertObject…)。所以现在它“起作用”了,但确实很难看@Alex Reynolds--因为我正试图使缓存数组与调用异步图像获取程序的对象数组保持同步,而且我不太可能按照它们启动的顺序获取获取程序。如果需要排序或排序数组,您可以先执行异步回迁,然后在完成回迁操作后创建一个已排序或有序的数组。请改为使用字典…键入“index”值Is
ArrayContainesIndex
也是您在NSArray类别中创建的吗?文档中没有提到这样的方法——坦率地说,如果存在这样的方法,我就使用它!对不起,我忘了那个。我已经用arrayContainsIndex:方法更新了答案。如果索引是负数会发生什么?如果索引是负数会发生什么?