2016-04-22 101 views
0

我找不到一种方法使用NSPredicate字符串获取数组中的第012项项目中的第个项目。例如:NSPredicate String获得第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; 
} 
+2

有没有您想要使用的谓词字符串,而不只是'阵列的理由[indexYouWant]'或'[array objectAtIndex:indexYouWant]'? – AdamPro13

+0

是的,我在做什么,我没有对数组本身的引用,我只能使用NSPredicateString进行查询。在这种情况下,我只是将过滤后的数组返回给我。 – Rafthecalf

+0

您可以将该数组存储在临时数组中并使用'objectAtIndex'获取第n个元素 – Lion

回答

0

如果你想得到一个项目,你不会收到一个NSArray,因为你只会收到一个对象。

您可以使用NSPredicate按数组中对象的名称进行搜索。但是你说什么,那不是你想要的。

您可以使用[array objectAtIndex:index];,它返回索引中指示位置的对象。

如果你想要一个对象的索引,你可以使用[array indexOfObject:object];,它返回对象的索引。

0

谓词不知道数组索引。他们只知道他们在任何时候被呈现的单个对象,以及该对象是否使谓词为真或假。

您在评论中呈现此问题的方式绝对没有意义。如果你可以得到数组的过滤版本,那么你可以得到数组。这里是你如何使用您展示这样做的方法:

NSArray * fullList = [theAPI filterUsingNSPredicate:@"TRUEPREDICATE"]; 

TRUEPREDICATE is a special value for predicate strings始终计算为真。当用谓词过滤数组时,结果将与原始数据相同。

您现在有一个对数组的引用,并且可以像通常那样对其进行索引。