6

一部のフィルターがオプションである場合、NSPredicate を構築する最善の方法は何だろうか?

これは基本的にフィルター用であるため、一部のオプションが選択されていない場合は、それらでフィルター処理しません

例えば。フィルターにオプション 1 とオプション 2 が設定されている場合。

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"option1 = %@ AND option2 = %@] ....

それ以外の場合は、option1 NSPredicate* predicate = [NSPredicate predicateWithFormat:@"option1 = %@] ....

重要なのは、フィルタリングする 10 の異なるオプションがあることです。そのため、10x10 の可能な組み合わせをコーディングする必要はありません。

ありがとう

4

2 に答える 2

17

ジョン、「サブ述語」をテンプレートとして作成および保持する方法を見てから、ロジック ブランチを使用して複合述語を作成し、フィルタリングを実行します。

/* Retain these predicate templates as properties or static variables */
NSPredicate *optionOneTemplate = [NSPredicate predicateWithFormat:@"option1 = $OPTVALUE"];
// .. and so on for other options

NSMutableArray *subPredicates = [NSMutableArray arrayWithCapacity:10];

/* add to subPredicates by substituting the current filter value in for the placeholder */
if (!!optionOneValue) {
  [subPredicates addObject:[optionOneTemplate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:optionOneValue forKey:@"OPTVALUE"]]];
}
// .. and so on for other option values

/* use the compound predicate to combine them */
NSPredicate *filterPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];

// Now use your filterPredicate

述語テンプレートのセットを適切に整理するために辞書を使用することもできますが、上記の例は基本的な手順を示しています。

ロブ。

于 2010-04-15T18:42:39.400 に答える
1

predicateWithFormat:NSString を取ります。したがって、選択したオプションに基づいて文字列を作成し (for ループを使用して NSMutableString に追加するなど)、それをに渡すだけです。predicateWithFormat:

于 2010-04-15T08:02:04.737 に答える