1

我想根据多个参数(如标题、结束日期等)搜索我的 eventList 数组...当我只使用一个参数标题(如 [cd] %@)时,我正在使用以下代码,它工作得很好

        NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimmed = [searchBar.text stringByTrimmingCharactersInSet:whitespace];
        if([trimmed isEqualToString:@""]==NO)
        {
            //        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title like[cd] %@",[NSString stringWithFormat:@"*%@*", searchBar.text]];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title like[cd] %@ ||  enddate like[cd] %@  ",[NSString stringWithFormat:@"*%@*", searchBar.text],[NSString stringWithFormat:@"*%@*", searchBar.text]];

            NSLog(@"Main Array:%@",arrMain);
            eventsList =(NSMutableArray*) [arrMain filteredArrayUsingPredicate:predicate];
            [eventsList retain];
            NSLog(@"Search Result:%@",eventsList);
            [eventTable reloadData];
        }

我试过
NSPredicate predicate = [NSPredicate predicateWithFormat:@"(title like[cd] %@) OR (enddate like[cd] %@)",[NSString stringWithFormat:@" %@ ", searchBar.text],[ NSString stringWithFormat:@" %@*", searchBar.text]];

它也有效,但不准确,因为我正在搜索特定日期,它不会显示,但如果我写 2 或 p 或 a 它只适用于某些结果......所以我可以说它不完美,我的 enddate 是带有格式的字符串2012-09-04 18:28:02 谁能帮我解决这个问题....

4

2 回答 2

3

将适当的单个谓词集合组装成 NSCompoundPredicate

如在

NSMutableArray *parr = [NSMutableArray array];
if([brand_one length]) { 
    [parr addObject:[NSPredicate predicateWithFormat:@"(title like[cd] %@) OR (enddate like[cd] %@) ",[NSString stringWithFormat:@"*%@*", searchBar.text],[NSString stringWithFormat:@"*%@*", searchBar.text]]];
}
if([brand_two length]) { 
     // etc 
}

NSCompoundPredicate *cpred = [NSCompoundPredicate andPredicateWithSubpredicates:parr];

您可以将谓词与 orPredicateWithSubpredicates: 和 andPredicateWithSubpredicates: 叠加,并且 NSCompoundPredicate 作为 NSPredicate 本身可以复合。

请参阅http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSCompoundPredicate_Class/Reference/Reference.html

于 2012-09-04T17:30:45.277 回答
0

完成

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(title like[cd] %@) OR (enddate like[cd] %@) ",[NSString stringWithFormat:@"*%@*", searchBar.text],[NSString stringWithFormat:@"*%@*", searchBar.text]];

我检查了我的数据库,它包含 2012-09-04 18:28:02 格式的日期,并且我以其他格式显示。

于 2012-09-04T17:09:17.783 回答