[英]NSPredicate String to get n'th item in array
我找不到使用NSPredicate
字符串获取数组中第n个项目的方法。 例如:
//You cannot touch or modify the code inside this method. You can only use the predicate string param to filter the array.
- (NSArray *)filterUsingNSPredicate:(NSString *)PredicateString
{
NSArray *array = @[
@"firstItem",
@"secondItem",
@"thirdItem",
@"fourthItem",
];
NSPredicate *pred = [NSPredicate predicateWithFormat:PredicateString];
NSArray *filtered = [array filteredArrayUsingPredicate:pred];
NSLog(@"This is the second item in the array! %@",filtered); //Thats the only thing in the array.
return filtered;
}
如果要获取项目,则不会收到NSArray,因为您只会收到一个对象。
您可以使用NSPredicate通过数组中的对象名称进行搜索。 但是你说的不是你想要的。
您可以使用[array objectAtIndex:index];
,它将返回您在索引中指示的位置的对象。
如果需要对象的索引,则可以使用[array indexOfObject:object];
,返回对象的索引。
谓词不了解数组索引。 他们只知道一次与他们一起出现的单个对象,以及该对象使谓语为真还是假。
您在评论中提出此问题的方式绝对没有道理。 如果可以获得阵列的过滤版本,则可以得到阵列。 这是您使用显示的方法的方式:
NSArray * fullList = [theAPI filterUsingNSPredicate:@"TRUEPREDICATE"];
TRUEPREDICATE
是谓词字符串的一个特殊值 ,始终TRUEPREDICATE
true。 当使用该谓词过滤数组时,结果将与原始数组相同。
现在,您有了对该数组的引用,并且可以像往常一样对它进行索引。
您可以使用以下块https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/#//apple_ref/occ/clm/NSPredicate/predicateWithBlock%3A创建谓词,以获取谓词第6个元素(从0开始的索引5):
__block NSInteger index = 0;
NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary<NSString *, id> *bindings)(
return index++ == 5;
)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.