wagashi
wagashi

Reputation: 894

ios what is wrong with my simple loop?

NSMutableArray *noDup = [[NSMutableArray alloc]init];
NSMutableArray *dup = [[NSMutableArray alloc]init];

for (NSString *first in newsmall)
{
    BOOL hasfound = NO;
    //NSLog (@"first %@", first);

    for (NSString *second in newbig) 
    {
        //NSLog (@"second %@", second);
        if ([second isEqualToString:first])
        {
            [dup addObject:first];
            hasfound = YES;
            break;
        }
    }

    if (!hasfound)
    {
        //NSLog (@"has not found %@", first);
        [noDup addObject:first];
    }
}

newsmall is a small array of only strings and newbig is a big array of only strings. The app shuts itself without any debug warning. NSLog showed "first" and "second", but not "has not found". How come?

Upvotes: 1

Views: 200

Answers (2)

hoshi
hoshi

Reputation: 1707

Your inner loop can be replaced with containsObject: method as follows:

for (NSString *first in newbig) {
    if ([newsmall containsObject:first]) {
        [dup addObject:first];
    } else {
        [noDup addObject:first];
    }
}

Also, converting newsmall to a NSSet will increase speed.

Upvotes: 0

Michael Dautermann
Michael Dautermann

Reputation: 89509

Oh, duhhhhh. I understand your problem now.

Reverse the order in which your arrays are being compared. If you want to find which strings in newbig do not exist in newsmall, iterate across newbig first while looking to see which enumerated word in newbig exists in newsmall.

The code looks like this (and only two lines of code have changed):

NSMutableArray *noDup = [[NSMutableArray alloc]init];
NSMutableArray *dup = [[NSMutableArray alloc]init];

for (NSString *first in newbig)
{
    BOOL hasfound = NO;
    //NSLog (@"first %@", first);

    for (NSString *second in newsmall) 
    {
        //NSLog (@"second %@", second);
        if ([second isEqualToString:first])
        {
            [dup addObject:first];
            hasfound = YES;
            break;
        }
    }

    if (!hasfound)
    {
        //NSLog (@"has not found %@", first);
        [noDup addObject:first];
    }
}

See the subtle difference?

Upvotes: 3

Related Questions