AR89
AR89

Reputation: 3638

Objective-c: find the last index of an element in a NSArray

I have a NSArray, and I want to find the last occurrence of an element. For example:

[apple, oranges, pears, apple, bananas];
int i = lastIndexOf("apple");
out: i == 3;

I'm struggling to find a simple solution looking an the APIS, but there aren't example so it's pretty hard to understand which function I should use.

Upvotes: 4

Views: 3077

Answers (3)

Tejas Shirodkar
Tejas Shirodkar

Reputation: 1

If anyone wants a reusable method with categories, I had written one for lastIndexOf.

Code can be found and freely used from here -

http://www.tejasshirodkar.com/blog/2013/06/nsarray-lastindexof-nsmutablearray-lastindexof/

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385700

NSUInteger index = [array indexOfObjectWithOptions:NSEnumerationReverse
    passingTest:^(id obj, NSUInteger i, BOOL *stop) {
        return [@"apples" isEqualToString:obj];
    }];

If the array doesn't contain @"apples", index will be NSNotFound.

Upvotes: 8

Daniel
Daniel

Reputation: 23359

NSArray has indexOfObjectWithOptions:passingTest:, this will allow you to search in reverse.

For example:

NSArray *myArr = @[@"apple", @"oranges", @"pears", @"apple", @"bananas"];
NSString *target = @"apple";

NSUInteger index = [myArr indexOfObjectWithOptions:NSEnumerationReverse
                                      passingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
                                          return [target isEqualToString:obj];
                                      }];

You can find out more details of this method in the Documentation by Apple.

Upvotes: 3

Related Questions