Counter in while within while not working
I'm having a strange problem with the following code:
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++;
}
This code retrieves al the entries from the "dames" array which are stated in the "finalWhatsNew" array. Problem with this is that the if is only get called the first time.
To make it a little bit clearer, the whole code is working fine, but as soon "i" is ++ to 1. the if statement isn't called. It looks like ios i canceling it out after the first time for performance reason or somethins like that. Anybody has any ideas?
Thnx!!!
After inner loop is finished for the first time the o
counter is equal to array's count and so it won't enter the loop again. To make it work you must reset o
counter on each iteration of the outer loop:
while (i<c){
o = 0;
while (t > o)
...
Edit: For clearer code (and probably better performance) you can use fast enumeration instead of usual for/while loops:
for (NSString *searchId in whatsNewArray1){
for (YourObject *obj in dames){
if ([[obj productId] isEqualToString:searchId])
[finalWhatsNew addObject: obj];
}
}
Edit2: Also you can eliminate 2nd loop by using NSPredicate to filter your array:
for (NSString *searchId in whatsNewArray1){
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"productId == %@",searchId];
[finalWhatsNew addObjectsFromArray:[dames filteredArrayUsingPredicate:predicate]];
}
As Vladimir says, you need to reset o
after each iteration of the outer loop. Ideally you switch to for
-statements here, as they fit what you're doing exactly:
for (int i=0; i<c; ++i) {
// ...
for (int o=0; o<t; ++o) {
// ...
精彩评论