2016-04-22 97 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始終計算爲真。當用謂詞過濾數組時,結果將與原始數據相同。

您現在有一個對數組的引用,並且可以像通常那樣對其進行索引。