【问题标题】:NSArray removeObjectAtIndex ErrorNSArray removeObjectAtIndex 错误
【发布时间】:2012-09-08 14:20:50
【问题描述】:

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

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:终止调用抛出异常(lldb)

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

谢谢!

【问题讨论】:

  • 请注意,以这种方式使用isKindOfClass: 过滤数组内容是非常奇怪的。通常,使用isKindOfClass: 表示架构较弱。

标签: iphone objective-c ios xcode nsarray


【解决方案1】:

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

if(titlescopy.count > i)

【讨论】:

    【解决方案2】:

    这个问题的答案在你的日志中......

    * 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];
         }
    }
    

    【讨论】:

      【解决方案3】:

      //if(titlescopy.count >= i) ">=" 是错误的。把它变成“>”

      "i" 应该小于数组的计数 a=

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多