Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 937
AR89 Avatar asked Dec 21 '22 14:12

AR89


1 Answers

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.

like image 200
rob mayoff Avatar answered Jan 10 '23 23:01

rob mayoff