【问题标题】:IndexOfObject return 2147483647IndexOfObject 返回 2147483647
【发布时间】:2012-06-07 10:22:34
【问题描述】:

我有一个包含 10 个项目的数组。当我为元素编号 9 和元素编号 10 调用“IndexOfObject”时,Xcode 返回异常:“NSRangeException

原因:'_[_NSCFArray objectAtIndex:] index:2147483647 超出 边界(10)'。

从之前的NSLog 中,我看到这两个元素存在于数组中,但indexOfObject 没有找到它们。为什么?

我的代码是:

    NSDictionary * headConfig =[avatarDictionaryToSave objectForKey:@"head_dictionary"];
    NSString * headImage =[headConfig objectForKey:@"layer_key"];
    NSString * pathFace =[[NSBundle mainBundle]pathForResource:@"Face" ofType:@"plist"];
    NSLog(@"%@", headImage);

    NSArray *arrayFace =[NSArray arrayWithContentsOfFile:pathFace];
    NSLog(@"the  elements are: %@", arrayFace);//here headImage is present
    int index =[arrayFace indexOfObject:headImage];
    NSLog(@"the index is %d", index);

【问题讨论】:

  • 你是如何检索索引的?
  • 您似乎混淆了indexOfObjectobjectAtIndex?前者会找到对象,而后者会在数组中的索引处检索对象?

标签: iphone nsarray nsrangeexception


【解决方案1】:

indexOfObject: 在数组中不存在对象时返回NSNotFoundNSNotFound 定义为 NSIntegerMax(在 iOS 32 位上 == 2147483647)。

看来您要查找的对象不存在。

【讨论】:

  • 或者在 64 位架构上,返回 9223372036854775807。
【解决方案2】:
     Please change the coding of adding the array values as I mentioned below.
    //  [arr_values addObject:[dictionary valueForKey:@"Name"]];
     [arr_values addObject:[NSString stringWithFormat:@"%@",[dictionary valueForKey:@"Name"]]];

   When target array elements are not in string format then while we using the 
indexOfObject then that value can't able to find in the target array. So please try to 
change the value of object as mentioned above while adding into array.

【讨论】:

  • 供您参考,这也是一个案例的失败之一。我遇到了同样的情况,所以我在这里回答了。如果您尝试其他一些解决方案仍然无法找到解决方案,那么也试试这个。
【解决方案3】:

默认情况下,假定一个整数是有符号的。

换句话说,编译器假定将调用一个整数变量来存储负数或正数。这限制了范围可以在任一方向上达到的范围。

例如,32 位 int 的范围为 4,294,967,295。实际上,因为该值可能是正数或负数,所以范围实际上是−2,147,483,648+2,147,483,647

如果我们知道永远不会调用变量来存储负值,我们可以将其声明为无符号,从而将(正)范围扩展到0+4,294,967,295

一个无符号整数指定如下:

unsigned int myint;

【讨论】:

  • 这不能回答问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2013-03-10
  • 2011-03-11
  • 2013-09-09
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
相关资源
最近更新 更多