Peter Warbo
Peter Warbo

Reputation: 11700

Objective-C ugly code?

I have some Objective-C code that does the job for me. But is it ugly (inefficient). Can it be performed better with for-each loops?

See this code please:

for (int i = 0; i < [careerIds count]; i++) {

    NSString *titleString = [[titles objectAtIndex:i] stringValue];
    if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location != NSNotFound) {
        // Don't add the id
    } else {
        [ids addObject:[[careerIds objectAtIndex:i] stringValue]];
    }

}

Upvotes: 0

Views: 814

Answers (3)

mikeytdan
mikeytdan

Reputation: 254

Assuming careerIds is a NSArray or NSMutableArray and that you're add NSString objects to it, you can do this:

for (NSString *titleString in careerIds) {

    if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location != NSNotFound) {
        // Don't add the id
    } else {
        [ids addObject: titleString];
    }
}

[ids addObject:[[careerIds objectAtIndex:i] stringValue]];

Upvotes: 0

Caleb
Caleb

Reputation: 124997

I don't think the code that you have is particularly ugly -- there's nothing at all wrong with using an indexed for loop as you've done. The only thing I might change would be to invert the sense of the if statement so that you avoid the empty // Don't add the id line. Here's one way:

for (int i = 0; i < [careerIds count]; i++) {

    NSString *titleString = [[titles objectAtIndex:i] stringValue];

    if (([titleString length] > 0) && 
        ([titleString rangeOfString:@"Intresseanmälan"].location == NSNotFound))
    {
        [ids addObject:[[careerIds objectAtIndex:i] stringValue]];
    }

}

To get to the heart of your question, no, I don't believe it's possible to use the fast enumeration version of the for loop to iterate over the contents of two separate containers at the same time. You can use it with one, but as I pointed out in a comment, you then have to use -indexOfObject: to recover the index of the current object so that you can get the corresponding item from the other array using -objectAtIndex:.

Upvotes: 2

JeremyP
JeremyP

Reputation: 86651

Can it be performed better with for-each loops?

Yes.

for (id title in careerIds) {

    NSString *titleString = [title stringValue];
    if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location != NSNotFound) {
        // Don't add the id
    } else {
        [ids addObject:titleString];
    }
}

Or if you want to be really flash:

for (NSString* titleString in [careerIds valueForKey: @"stringValue"]) {

    if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location != NSNotFound) {
        // Don't add the id
    } else {
        [ids addObject:titleString];
    }
}

No. :-)

Upvotes: 0

Related Questions