[英]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. 我有一个NSArray,我想找到一个元素的最后一个出现。 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. 我很难找到一个看APIS的简单解决方案,但是没有例子,所以我很难理解我应该使用哪个函数。
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
. 如果数组不包含@"apples"
,则index
将为NSNotFound
。
NSArray
has indexOfObjectWithOptions:passingTest:
, this will allow you to search in reverse. NSArray
有indexOfObjectWithOptions:passingTest:
,这将允许您反向搜索。
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 . 您可以在Apple的文档中找到有关此方法的更多详细信息。
If anyone wants a reusable method with categories, I had written one for lastIndexOf. 如果有人想要一个带有类别的可重用方法,我已经为lastIndexOf写了一个。
Code can be found and freely used from here - 代码可以在这里找到并自由使用 -
http://www.tejasshirodkar.com/blog/2013/06/nsarray-lastindexof-nsmutablearray-lastindexof/ http://www.tejasshirodkar.com/blog/2013/06/nsarray-lastindexof-nsmutablearray-lastindexof/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.