如何使用NSPredicate检索NSArray的索引? [英] How retrieve an index of an NSArray using a NSPredicate?
问题描述
我知道如何使用 NSPredicate
检索 NSArray
的索引?
I would know how retrieve an index of an NSArray
using a NSPredicate
?
NSArray *array = [NSArray arrayWithObjects:
@"New-York City",
@"Washington DC",
@"Los Angeles",
@"Detroit",
nil];
我应该使用哪种方法来获取Los Angles的索引a NSString
NB: @Los An
或 @geles
应返回相同的索引..
Wich kind of method should I use in order to get the index of "Los Angles" by giving only a NSString
NB: @"Los An"
or @"geles"
should return the same index..
推荐答案
使用NSPredicate,您可以获得包含搜索的字符串数组string(似乎没有内置方法来获取元素索引):
Using NSPredicate you can get array of strings that contain your search string (it seems there's no built-in method to get just element indexes):
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchString];
NSArray *filteredArray = [array filteredArrayUsingPredicate: predicate];
您只能使用 indicesOfObjectsPassingTest获取索引:
方法:
NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
NSString *s = (NSString*)obj;
NSRange range = [s rangeOfString: searchString];
return range.location != NSNotFound;
}];
如果您只想获得一个包含字符串的元素,您可以使用类似的 indexOfObjectPassingTest:
方法。
If you want to get just one element containing your string you can use similar indexOfObjectPassingTest:
method for that.
这篇关于如何使用NSPredicate检索NSArray的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!