NSArray removeObjectAtIndex错误

时间:2012-09-08 14:20:50

标签: iphone objective-c ios xcode nsarray

我正在使用以下代码检查某个对象是否存在,然后再将其删除:

if(titlescopy.count >= i)
{
   if([[titlescopy objectAtIndex:i] isKindOfClass:[NSString class]])
   {
       [titlescopy removeObjectAtIndex:i];
   }
}

但是,我收到此错误:

  

*由于未捕获的异常'NSRangeException'终止应用程序,原因:'* - [__ NSArrayM objectAtIndex:]:索引2超出边界[0 ..   1]”    * 第一次抛出调用堆栈:(0x365a56c3 0x3881e97f 0x364f1055 0x494b 0x37fdb8d5 0x37fe7d75 0x37fe7a81 0x38001ddd 0x38001b97 0x172bd   0x3805f8e5 0x3805f897 0x3805f875 0x3805f12b 0x3805f621 0x37f87d29   0x37f74f29 0x37f74843 0x34ea25d3 0x34ea2203 0x3657a593 0x3657a537   0x365793b9 0x364ec39d 0x364ec229 0x34ea131b 0x37fc88f9 0x283b 0x2798)   libc ++ abi.dylib:terminate调用抛出异常(lldb)

为什么会这样?我正在使用的代码应该在尝试删除它之前检查该对象是否存在,但显然不是。

谢谢!

3 个答案:

答案 0 :(得分:5)

Objective-C中的数组索引从0开始,因此i = titlescopy.count超出范围。将您的if语句更改为:

if(titlescopy.count > i)

答案 1 :(得分:4)

答案就在你的日志本身......

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[_**_NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'**

你指的是超出范围的索引...例如,考虑你的数组大小是3,但你引用的是第4个对象。所以最好是检查下面的索引是否计数。如果是这样继续你想要的东西。

// mistake is "i" should not be equal to count...
if(i < titlescopy. count)
{
     if([[titlescopy objectAtIndex:i] isKindOfClass:[NSString class]])
     {
         [titlescopy removeObjectAtIndex:i];
     }
}

答案 2 :(得分:0)

// if(titlescopy.count&gt; = i)“&gt; =”错误。把它变成“&gt;”

“i”应小于数组的计数a =

if(titlescopy.count > i)
{
    if([[titlescopy objectAtIndex:i] isKindOfClass:[NSString class]])
    {
        [titlescopy removeObjectAtIndex:i];
    }
}