Take the 2-minute tour ×

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);

        NSLog(@"dames %i", i);
        if ([[[dames objectAtIndex:o] productId] isEqualToString:[whatsNewArray1 objectAtIndex:i]]){
            [finalWhatsNew addObject:[dames objectAtIndex:o]];
            NSLog(@"inner dames%i", 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?


share|improve this question
How many objects are in whatsNewArray1? Could you add some more NSLog statements to understand what is happening and post the output? –  sergio Jul 25 '11 at 13:47

2 Answers 2

up vote 3 down vote accepted

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]];
share|improve this answer
Oh great! Thnx this worked –  Jos Jul 25 '11 at 20:21

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 o=0; o<t; ++o) {
        // ...
share|improve this answer

Your Answer


