在NSMUtableArray中查看索引[i]处是否存在一个对象

3

如果一个数组中的索引[i]元素不在另一个(或当前)数组中,我希望能够查看这些人。例如,如果我的数组看起来像这样:

[wer, wer4 , wer5 , werp , klo ...

那么我想知道aExerciseRef.IDE(例如为"sdf")是否存在于索引[i]处。

我假设我需要使用某种迭代器来实现。

for( int i = 0; i < 20; i++ )
{
   if([instruct objectAtIndex:index2 + i] != [instruct containsObject:aExerciseRef.IDE] )                       
   NSLog(@"object doesn't exist at this index %i, i );
   else
   NSLog(@"well does exist")
}

我知道这不起作用,只是为了阐述我的目标。

编辑:

我将尽力详细说明并更加具体。

1) 首先,每次调用aExerciseRef.IDE时都会发生更改,因此有一次它是“ret”,另一次则是“werd”。

2) 想象一下一个数组被填充了aExerciseRef.IDE's,然后我想比较这个数组中的元素是否存在于instruct数组中。

所以我想看看在位置2(wtrk)的元素是否存在。

[wer, wtrk, wer , sla ... 

在填充aExerciseRef.IDE的数组中存在。

我希望这次表达更清晰了。

2个回答

2

伟大的Sir Lord在某种程度上是正确的。是的,您的比较是错误的。但他的解决方案不可行。

这里有一个可行的解决方案:

if (index < [anArray count] && [[anArray objectAtIndex:index] isEqual:anObject]) {
  NSLog(@"Got it!");
} else {
  NSLog(@"Don't have it.");
}

另外,您也可以使用containsObject:方法来实现相同的功能:

if ([anArray containsObject:aExerciseRef.IDE]) {
  NSLog(@"Got it!");
} else {
  NSLog(@"Don't have it.");
}

第二个选项不会给你对象的索引,但可以轻松地通过以下方式进行纠正:
NSInteger index = NSNotFound;
if ([anArray containsObject:aExerciseRef.IDE]) {
  index = [anArray indexOfObject:aExerciseRef.IDE];
  ...
}

选择使用 -isEqual: 还是 -isEqualTo: 有什么特别的原因吗? - Rik Smith-Unna

0

你的例子根本没有意义,也没有任何澄清问题的作用。你正在比较一个带有类型 (id) 的表达式。

[instruct objectAtIndex:index2 + i]

并且一个类型为BOOL

[instruct containsObject:aExerciseRef.IDE]

如果你要查找的对象在数组中的索引为x,那么显然对该数组执行containsObject操作将返回YES。

如果你想要实现的只是标题中所述的内容,那么很简单:

if ([[anArray objectAtIndex:index] == anObject])
  NSLog (@"Got it!");
else
  NSLog (@"Don't have it.");

2
两个问题:索引可能超出范围,并且您无法使用“==”作为方法调用来测试相等性。 - Dave DeLong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接