6

UITableView'sとを使用してデータをフィルタリングしようとしていUISearchDisplayControllerますNSCompoundPredicateUILabels検索内ですべてフィルタリングしたい3つのカスタムセルがあるため、 NSCompoundPredicate

  // Filter the array using NSPredicate(s)

  NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"SELF.productName contains[c] %@", searchText];
  NSPredicate *predicateManufacturer = [NSPredicate predicateWithFormat:@"SELF.productManufacturer contains[c] %@", searchText];
  NSPredicate *predicateNumber = [NSPredicate predicateWithFormat:@"SELF.numberOfDocuments contains[c] %@",searchText];

  // Add the predicates to the NSArray

  NSArray *subPredicates = [[NSArray alloc] initWithObjects:predicateName, predicateManufacturer, predicateNumber, nil];

  NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];

ただし、これを行うと、コンパイラは次のように警告します。

タイプ「NSPredicate*」の式で「NSCompoundPredicate*_strong」を初期化する互換性のないポインター型

私がオンラインで見たすべての例はこれとまったく同じことをしているので、私は混乱しています。NSCompoundPredicate orPredicateWithSubpredicates:メソッドは最後の(NSArray *)パラメーターを取りますので、私は本当に混乱しています。

どうしたの?

4

3 に答える 3

13

orPredicateWithSubpredicates:NSPredicate*を返すように定義されています。コードの最後の行を次のように変更できるはずです。

NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];

...そしてまだすべてのcompoundPredicatesが適用されています。

于 2012-11-30T14:39:03.823 に答える
13

まず第一に、「含む」の使用は非常に遅いです、多分「始まり」を考えますか?第二に、あなたが望むものは次のとおりです。

NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];

3つ目は、次のようなことです。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.productName beginswith[cd] %@ OR SELF.productManufacturer contains[cd] %@", searchText, searchText];
于 2012-11-30T14:45:22.757 に答える
0

上記の回答に基づいて作成した便利なメソッドを次に示します(ありがとうございます)。

フィルタ項目の配列と検索条件を表す文字列を送信することにより、NSPredicateを動的に作成できます。

元のケースでは、検索条件が変更されるため、文字列ではなく配列にする必要があります。しかし、それはとにかく役立つかもしれません

- (NSPredicate *)dynamicPredicate:(NSArray *)array withSearchCriteria:(NSString *)searchCriteria
{
    NSArray *subPredicates = [[NSArray alloc] init];
    NSMutableArray *subPredicatesAux = [[NSMutableArray alloc] init];
    NSPredicate *predicate;

    for( int i=0; i<array.count; i++ )
    {
        predicate = [NSPredicate predicateWithFormat:searchCriteria, array[i]];
        [subPredicatesAux addObject:predicate];
    }

    subPredicates = [subPredicatesAux copy];

    return [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
}
于 2015-08-28T20:32:46.993 に答える