2010-03-29 47 views
2

我建立一個carArray,並希望有條件地篩選內容,使用NSPredicate,就像這樣:如何使用NSPredicate返回整個集合/數組?

NSPredicate *pred; 
switch (carType) { 
    case FreeCar: 
    pred = [NSPredicate predicateWithFormat:@"premium = NO"]; 
    break; 
    case PremiumCar: 
    pred = [NSPredicate predicateWithFormat:@"premium = YES"]; 
    break; 
    default: 
    pred = [NSPredicate predicateWithFormat:@"SOME PREDICATE THAT RETURNS EVERYTHING"]; 
    break; 
} 
self.carArray = [aCarArrayIGotFromSomewhere filteredArrayUsingPredicate:pred]; 

我的問題是,什麼是我在存根作爲SOME PREDICATE THAT RETURNS EVERYTHING值正確的語法,返回數組/集合中的所有實例?

回答

7

要返回所有的內容的給定陣列/組:

夫特:

NSPredicate(value: true)

例如:

let array : NSArray = ["a", "b", "c", "d", "e"] let predicate = NSPredicate(value: true) array.filteredArrayUsingPredicate(predicate)

收率:

["a", "b", "c", "d", "e"]

要排除所有的內容的給定陣列/組:

夫特:

NSPredicate(value: false)

例如:

let array : NSArray = ["a", "b", "c", "d", "e"] let predicate = NSPredicate(value: false) array.filteredArrayUsingPredicate(predicate)

收率:

[]

+2

不幸的是,相關文檔在如何使用這個TRUEPREDICATE thingie方面並沒有太多沉默。無論如何我都無法解決。所以,我搜索堆棧溢出和曾經沒有更明智的:( – 2010-08-02 08:02:20

+0

我第二需要一個例子。我嘗試了直觀的解決方案(即只傳遞TRUEPREDICATE作爲格式字符串,我得到了一個N​​SInvalidArgumentException) – vargonian 2012-07-10 22:18:14

+3

而不是[NSPredicate predicateWithFormat :@「TRUEPREDICATE」]你可以做[NSPredicate predicateWithValue:YES] – valexa 2014-01-23 13:23:46

3

對於始終爲真或始終爲false的情況,您可以使用[NSPredicate predicateWithValue:YES][NSPredicate predicateWithValue:NO]