我在使用以下代码时遇到了一个奇怪的问题:
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/