条件が満たされない場合に true を返す NSPredicate を作成する
-
19-09-2019 - |
質問
現在、次のコードがあります
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"];
[resultsArray filterUsingPredicate:pred];
これは、「-」を含む要素を含む配列を返します。これの逆を実行して、「-」を含まないすべての要素が返されるようにしたいと考えています。
これは可能でしょうか?
さまざまな場所で NOT キーワードを使用してみましたが、役に立ちませんでした。(Apple のドキュメントに基づいて、私はそれがとにかく機能するとは思いませんでした)。
これをさらに進めるために、配列の要素に含めたくない文字の配列を述語に提供することは可能ですか?(配列は文字列のロードです)。
解決
私は Objective-C の専門家ではありませんが、 ドキュメントではこれが可能であることを示唆しているようです. 。やってみました:
predicateWithFormat:"not SELF contains '-'"
他のヒント
あなたがすでに持っている述語を否定するカスタム述語を構築することができます。実際には、既存の述語を取っているとNOT演算子のように動作し、別の述語でそれを包むます:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"];
NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred];
[resultsArray filterUsingPredicate:pred];
// 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];
私は、しかし、その効率について何らの保証をしない、それはおそらく、最初の最終列からほとんどの文字列を排除する可能性がある文字を入れることをお勧めしますようにフィルタリングすることができますできるだけ短絡など、多くの比較ます。
コメントをお勧めします NSNotPredicateType
で説明されているように、 Apple のドキュメント.
所属していません StackOverflow