2009-07-22 12 views
9

私は現在、コード条件が満たされない場合はtrueを返しますNSPredicateを書く

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

これが含まれている要素を持つ配列を返すの以下の部分を持っています「 - 」。私はこれを逆にしたいので、 ' - 'を含まないすべての要素が返されます。

これは可能ですか?

さまざまな場所でNOTキーワードを使用しようとしましたが、役に立たないです。 (Appleのドキュメントに基づいて、とにかく動作するとは思わなかった)。

これをさらに行うには、配列の要素に入れたくない文字の配列を述語に与えることは可能ですか? (配列は文字列の読み込みです)。

+0

変更があったタイトルは、この質問が何を求めているかをよりよく反映するように変更されました。 –

答えて

27

私はObjective-Cエキスパートではありませんが、documentation seems to suggest this is possibleです。あなたは試してみました:

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

ありがとうございます。私はその文書全体を読んでいないのです。私が試していない唯一の場所は自分の前でした! – JonB

+0

うれしい私は助けることができました。 :) –

+0

+1、Sweeeeeeet! – EmptyStack

8

は、あなたが既に持っている述語を否定するカスタム述語を構築することができます。あなたが通過して構築できるので、

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

NSCompoundPredicateクラスがサポートAND、OR、およびNOT述語タイプ:実際には、既存の述語を取っていると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];

:ような何かを試してみてください可能な限り多くの比較を短絡してください。

関連する問題