Objective-c: find last element index in NSArray

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

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

I am trying to find a simple solution looking at APIS, but there is no example, so it’s quite difficult to figure out which function I should use.

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

If the array does not contain @"apples" , index will be NSNotFound .

+7
source

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

For instance:

 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]; }]; 

More information on this method can be found in Apple's documentation .

+3
source

If someone wants to use a reusable method with categories, I wrote one for lastIndexOf.

The code can be found and freely used here -

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

0
source

Source: https://habr.com/ru/post/1440360/


All Articles