NSPredicates に関するいくつかのトピックについて StackOverflow を確認しました。それらはすべて正しい方向を指していますが、すべてについて重要な何かが欠けているに違いありません。
製品のリストを含む NSMutableArray があります。各製品には、ブランド、カテゴリ、タイプなどのいくつかのプロパティがあります。
ここで、ユーザーが NSPredicates を使用してその NSMutableArray をフィルタリングできるようにしたいので、選択したフィルターのいずれかが空白の場合、そのフィルターを使用しないでください。
ただし、たとえば、すべてのフィルターがオンになっている場合: カテゴリー B およびタイプ C のブランド A でフィルターすると、カテゴリー B およびタイプ C のブランド A のみが表示されます。
次にカテゴリ B の選択を解除すると、タイプ C のブランド A がフィルタされます。
私はいくつかのコードを書きましたが、主に空の NSMutableArray を返すので、NSPredicates がオフになっていると思います。
また、述語を実行する前に「すべての製品」の NSMutableArray をデフォルトにする必要があることもわかりました。そうしないと、新しいフィルター オプションが選択されたときに、既にフィルター処理された配列がフィルター処理されます。いくつかの BOOLean マジックで複数の配列を使用する必要がありますか、またはこれは NSPredicates を使用して解決できる問題ですか?
これが私のコードです:
-(void)filterTable
{
NSPredicate *brandPredicate;
NSPredicate *categoryPredicate;
NSMutableArray *compoundPredicateArray;
if( ![self.selectedBrand isEqual: @"Show All Brands"] || !(self.currentBrand == NULL))
{
brandPredicate = [NSPredicate predicateWithFormat:@"brand CONTAINS[cd] %@",self.currentBrand];
compoundPredicateArray = [ NSMutableArray arrayWithObject: brandPredicate ];
}
if( ![self.currentCategory isEqual: @"Show All Categories"] || !(self.currentCategory == NULL))
{
categoryPredicate = [NSPredicate predicateWithFormat:@"category CONTAINS[cd] %@",self.currentCategory];
[ compoundPredicateArray addObject: categoryPredicate];
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:
compoundPredicateArray ];
[self.tableData filterUsingPredicate:predicate];
[self.popNTwinBee dismissPopoverAnimated:YES]; // PopoverController
[self.tableView reloadData];
}