20

noobie 问题.. 检查 NSArray 或 NSMutableArray 的索引是否存在的最佳方法是什么。我到处找都无济于事!!

这是我尝试过的:

if (sections = [arr objectAtIndex:4])
{
    /*.....*/
}

或者

sections = [arr objectAtIndex:4]
if (sections == nil)
{
    /*.....*/
}

但两者都会引发“越界”错误,不允许我继续

(不要用 try catch 回复,因为那不是我的解决方案)

提前致谢

4

4 回答 4

18
if (array.count > 4) {
    sections = [array objectAtIndex:4];
}
于 2012-03-15T07:08:46.753 回答
2

如果您有一个整数索引(例如i),您通常可以通过检查数组边界来防止此错误,如下所示

int indexForObjectInArray = 4;
NSArray yourArray = ...

if (indexForObjectInArray < [yourArray count])
{
    id objectOfArray = [yourArray objectAtIndex:indexForObjectInArray];
}
于 2013-01-24T20:58:06.597 回答
0

请记住 NSArray 是按从0 到 N-1项的顺序排列的

您正在尝试超出限制access item,然后编译器将抛出.arraynilbound error

编辑:@sch 上面的回答显示了我们如何检查 NSArray 是否需要其中存在的有序项目。

于 2012-05-17T11:48:03.903 回答
0

您可以MIN像这样使用运算符静默失败[array objectAtIndex:MIN(i, array.count-1)],以获取数组中的下一个对象或最后一个对象。例如,当您想要连接字符串时可能很有用:

NSArray *array = @[@"Some", @"random", @"array", @"of", @"strings", @"."];
NSString *concatenatedString = @"";
for (NSUInteger i=0; i<10; i++) {  //this would normally lead to crash
    NSString *nextString = [[array objectAtIndex:MIN(i, array.count-1)]stringByAppendingString:@" "];
    concatenatedString = [concatenatedString stringByAppendingString:nextString];
    }
NSLog(@"%@", concatenatedString);

结果:“一些随机的字符串数组......”

于 2016-05-24T09:18:23.663 回答