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

巧了我就是萌 提交于 2019-12-10 18:05:04

问题


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.


回答1:


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.




回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/12940431/objective-c-find-the-last-index-of-an-element-in-a-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!