NSArray超出界限检查

spa*_*ker 17 cocoa nsmutablearray nsarray indexoutofboundsexception

noobie question ..检查NSArray或NSMutableArray的索引是否存在的最佳方法是什么.我到处搜索都没有用!

这是我尝试过的:

if (sections = [arr objectAtIndex:4])
{
    /*.....*/
}
Run Code Online (Sandbox Code Playgroud)

要么

sections = [arr objectAtIndex:4]
if (sections == nil)
{
    /*.....*/
}
Run Code Online (Sandbox Code Playgroud)

但两者都抛出一个"出界"错误,不允许我继续

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

提前致谢

sch*_*sch 17

if (array.count > 4) {
    sections = [array objectAtIndex:4];
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为Objective-c语言在这里有点愚蠢.如果`[array objectAtIndex:outOfBounds]`返回`nil`而不是崩溃,我会更舒服. (4认同)