您需要做的是为每个子句创建一个谓词。例如,让我们分解您的查询:
- 从交易中选择 *
- 类别在何处(类别列表)
- 和位置(位置列表)
- 并输入(类型列表)
- AND 注意包含[cd]“一些文字”
- AND 日期 >= fromDate AND 日期
基于此,您有 5 个谓词 (2-6)。那么让我们一一研究它们。
NSPredicate *inCategoryPredicate = [NSPredicate predicateWithFormat:@"Category IN %@", categoryList];
NSPredicate *locationPredicate = [NSPredicate predicateWithFormat:@"Location IN %@", locationList];
NSPredicate *typePredicate = [NSPredicate predicateWithFormat:@"Type IN %@", typeList];
NSPredicate *notePredicate = [NSPredicate predicateWithFormat:@"Note contains[c] %@", @"Some Text"];
NSPredicate *startDatePredicate = [NSPredicate predicateWithFormat:@"Date => @", fromDate];
NSPredicate *endDatePredicate = [NSPredicate predicateWithFormat:@"Date <= @", toDate];
现在您只需将它们加入到一个谓词中即可:苹果的文档指出 https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html:
您应该构建复合谓词以尽量减少
完工。正则表达式匹配尤其昂贵
手术。因此,在复合谓词中,您应该执行
正则表达式之前的简单测试;
话虽这么说,那么您应该首先从“简单”谓词开始。所以:
NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects: startDatePredicate, endDatePredicate, inCategoryPredicate, locationPredicate, typePredicate, notePredicate];
如果你对它进行 NSLog,你总是可以了解谓词 (sql where) 是什么样子。