NSPredicate を作成して NSFetchRequest に設定する。これが基本。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"price > %d", 1000]; [request setPredicate:predicate];
値段と数量、といった複数の条件で絞り込みたい場合。 条件が固定なら predicateWithFormat に渡すフォーマット文字列と値を変更すればいい。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"price > %d AND quantity > %d", 1000, 10]; [request setPredicate:predicate];
じゃあ、複数の条件を動的に決定したい場合は? NSCompoundPredicate 使えばいい。
NSMutableArray *whereArray = [NSMutableArray new]; [whereArray addObject:[NSPredicate predicateWithFormat:@"price > %d", 1000]]; if (self.isCheckQuantity) { [whereArray addObject:[NSPredicate predicateWithFormat:@"quantity > %d", 10]]; } NSCompoundPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:whereArray]; [request setPredicate:predicate];
上記は複数の条件を AND で結合しているけど、OR で結合することもできる。