我试图使用一个UITableView's和NSCompoundPredicate来过滤一个NSCompoundPredicate数据。我有一个带有3 UILabels的自定义单元格,我希望在搜索过程中对所有单元格进行过滤,从而获得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];但是,当我这样做时,编译器会警告我:
不兼容的指针类型使用'NSCompoundPredicate *_strong‘类型的表达式初始化'NSPredicate *’
我在网上看到的每一个例子都是一样的,所以我很困惑。NSCompoundPredicate orPredicateWithSubpredicates:方法在最后一个参数中接受一个(NSArray *),所以我真的很困惑。
怎么了?
发布于 2012-11-30 14:45:22
首先,使用“包含”很慢,考虑五月“开始”吗?其次,你想要的是:
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];第三,你可以做这样的事情:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.productName beginswith[cd] %@ OR SELF.productManufacturer contains[cd] %@", searchText, searchText];发布于 2012-11-30 14:39:03
orPredicateWithSubpredicates:被定义为返回NSPredicate*。您应该能够将最后一行代码更改为:
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];..。并且仍然应用了所有的compoundPredicates。
发布于 2015-08-28 20:32:46
下面是我根据上面的答案创建的一个有用的方法(非常感谢!)
它允许动态地创建一个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];
}https://stackoverflow.com/questions/13647089
复制相似问题