iphone - 不工作时计数器

标签 iphone objective-c ios while-loop

我在使用以下代码时遇到了一个奇怪的问题:

int c = [whatsNewArray1 count];
int t = [dames count];
int i = 0;
int o= 0;
NSMutableArray *finalWhatsNew = [[NSMutableArray alloc]init];
while (i<c){
    NSLog(@"teller array %i", i);

    while(t>o){
        NSLog(@"dames %i", i);
        if ([[[dames objectAtIndex:o] productId] isEqualToString:[whatsNewArray1 objectAtIndex:i]]){
            [finalWhatsNew addObject:[dames objectAtIndex:o]];
            NSLog(@"inner dames%i", i);
        }
        o++;
    }
    i++;
}

此代码从“dames”数组中检索“finalWhatsNew”数组中所述的所有条目。问题在于 if 仅在第一次被调用。

为了更清楚一点,整个代码工作正常,但是一旦“i”++ 到 1,就不会调用 if 语句。看起来 ios 我在第一次后出于性能原因或类似原因取消了它。有人有什么想法吗?

谢谢!!!

最佳答案

第一次内循环完成后,o计数器等于数组的计数,因此不会再次进入循环。要使其正常工作,您必须在外循环的每次迭代中重置 o 计数器:

while (i<c){
    o = 0;   
    while (t > o)
    ...

编辑:为了更清晰的代码(并且可能有更好的性能),您可以使用快速枚举而不是通常的 for/while 循环:

for (NSString *searchId in whatsNewArray1){
   for (YourObject *obj in dames){
        if ([[obj productId] isEqualToString:searchId])
           [finalWhatsNew addObject: obj];
   }
}

Edit2:您还可以通过使用 NSPredicate 来过滤数组来消除第二个循环:

for (NSString *searchId in whatsNewArray1){
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"productId == %@",searchId];
     [finalWhatsNew addObjectsFromArray:[dames filteredArrayUsingPredicate:predicate]];
}

关于iphone - 不工作时计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6817051/

相关文章:

iphone - 编写 iPhone 需求规范?

iphone - cocos2d中重复背景有黑边!

ios - 当尝试注销/放松回到主屏幕时,如果甚至没有 optional ,为什么会收到“找到零”错误?

ios - 页面 curl 过渡在动画结束时挂起的可能原因是什么?

ios - 自从升级到 iOS10 后,带有 NSRunLoop 的信号量无法正常工作

ruby - 在 Sinatra 中,提供 iPhone 布局与普通布局的最佳方式是什么?

ios - UITabBarController 和 UINavigationController 中的编辑按钮

ios - 在 Xcode 5 的每个地方重命名项目名称的最佳方法是什么?

ios - 动态创建的方法未被调用

iphone - 有没有办法连接 css 和 UI 自定义类