2009-07-22 99 views
9

我現在有下面的代碼段寫入如果條件沒有得到滿足,則返回true一個NSPredicate

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"]; 
[resultsArray filterUsingPredicate:pred]; 

這將返回與包含元素的數組「 - 」。我想做與此相反的事情,以便返回所有不包含' - '的元素。

這可能嗎?

我試過在各個位置使用NOT關鍵字但無濟於事。 (無論如何,我不認爲它會工作,基於Apple文檔)。

爲了做到這一點,是否有可能提供一個字符數組的謂詞,我不想在數組的元素? (該數組是一串字符串)。

+0

更改標題以更好地反映這個問題作爲問。 – 2009-07-22 16:31:08

回答

27

我不是Objective-C的專家,但是documentation seems to suggest this is possible。你有沒有嘗試過:

predicateWithFormat:"not SELF contains '-'" 
+0

謝謝,請幫我完整閱讀文檔。我沒有嘗試過的唯一的地方是在自我之前! – JonB 2009-07-22 16:27:58

8

你可以構建一個自定義謂詞來否定你已有的謂詞。實際上,你正在做一個現有的斷言和工作方式類似於NOT運算符另一個謂詞包裹它:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"]; 
NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred]; 
[resultsArray filterUsingPredicate:pred];

NSCompoundPredicate類支持AND,OR,和NOT謂詞的類型,所以你可以去通過,並建立一個大型複合謂詞,其中包含您不想在數組中使用的所有字符,然後對其進行過濾。嘗試是這樣的:

// Set up the arrays of bad characters and strings to be filtered 
NSArray *badChars = [NSArray arrayWithObjects:@"-", @"*", @"&", nil]; 
NSMutableArray *strings = [[[NSArray arrayWithObjects:@"test-string", @"teststring", 
        @"test*string", nil] mutableCopy] autorelease]; 

// Build an array of predicates to filter with, then combine into one AND predicate 
NSMutableArray *predArray = [[[NSMutableArray alloc] 
            initWithCapacity:[badChars count]] autorelease]; 
for(NSString *badCharString in badChars) { 
    NSPredicate *charPred = [NSPredicate 
         predicateWithFormat:@"SELF contains '%@'", badCharString]; 
    NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred]; 
    [predArray addObject:notPred]; 
} 
NSPredicate *pred = [NSCompoundPredicate andPredicateWithSubpredicates:predArray]; 

// Do the filter 
[strings filterUsingPredicate:pred];

我不作任何保證,而它的效率,不過,它可能把它很可能先消除從最終陣列中最字符串中的字符是一個好主意,這樣的過濾器可以儘可能多地進行短路比較。

1

我會推薦NSNotPredicateType,如所述。

相關問題