Jules
Jules

Reputation: 7766

Obj-C, function to return index of nsstring found in nsarray?

I've been looking to see if I can find a function like indexOf.

I have an array.

self.data = [[NSArray alloc] initWithObjects:@"apple", @"lemon", @"pear", nil];

Looking for a function to return which would look for lemon and return 1 ?

Upvotes: 1

Views: 302

Answers (2)

Jumhyn
Jumhyn

Reputation: 6777

Try this method.

-(int)indexOfString:(NSString *)string inArray:(NSArray *)array {
    for(int i=0; i<[array count]; i++) {
        if ([[array objectAtIndex:i] class] == [NSString class]) {
            if ([[array objectAtIndex:i] isEqualToString:string]) {
                return i;
            }
        }
    }
}

EDIT: The other answer using -indexOfObject: is better.

Upvotes: 0

Matthias Bauch
Matthias Bauch

Reputation: 90117

how about indexOfObject:?

NSUInteger index = [self.data indexOfObject:@"lemon"];

Upvotes: 7

Related Questions