While-Loop工作但不是if语句?

slo*_*n21 1 arrays iphone xcode if-statement while-loop

while我的代码中有这个循环.循环似乎工作正常,因为我i++在控制台中打印了我.但由于某种原因,它只是if第一次检查我的陈述.我只能在NSMutableArray被叫中添加一个标题sectionZeroTitleArray.我在这个循环中有很多数组,所以它可能会让人感到困惑.我会尽力解释.

这是我想要做的:循环遍历数组的长度(topicArray).如果数组的(topicArray)与其他数组(anotherArray)的第一个对象相同,则将具有与topicArray相同的索引(tit​​leArray)的对象添加到新的MutableArray(sectionZeroTitleArray).

我确定我做了一些愚蠢的事情,也许一整天没有盯着这个的人可以解决我的问题?谢谢,麻烦您了.

while (i < (topicArray.count)) {
  if ([topicArray objectAtIndex:i] == [anotherArray objectAtIndex:0]) {
   [sectionZeroTitleArray addObject:[titleArray objectAtIndex:i]];
  }
  NSLog(@"sectionZeroLoopCount: %d", i);
  i++;
 }
Run Code Online (Sandbox Code Playgroud)

Jac*_*kin 5

您在使用时检查指针是否相等==.你确定你要这么做吗?你期待的是什么类型?如果它是一个NSString,使用isEqualToString:,否则使用NSObjectisEqual:方法:

如果预期的类型是NSString:

if([[topicArray objectAtIndex:i] isEqualToString:[anotherArray objectAtIndex:0]]) {
   //...
}
Run Code Online (Sandbox Code Playgroud)

否则,你应该这样做:

if([[topicArray objectAtIndex:i] isEqual:[anotherArray objectAtIndex:0]]) {
   //...
}
Run Code Online (Sandbox Code Playgroud)