核心数据查询具有单个搜索字符串的多个列

时间:2011-02-18 02:11:02

标签: iphone objective-c cocoa-touch xcode core-data

我有一个简单的Core Data模型,它有两个字符串属性(大小和类别)。给定像'小部件'这样的搜索字符串,是否可以将匹配所有查询字的记录返回到至少一个属性(即所有具有'小'尺寸和'小部件'类别的记录)?我目前有:

NSString *search = @"small widget"
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", search, search];
...

这不会返回任何结果(因为没有类别或大小等于“小部件”)。有什么建议?请注意,搜索字符串将是用户从文本字段输入的,并且可以按任何顺序排列,因此我无法手动拆分。

2 个答案:

答案 0 :(得分:2)

我没有测试过,但看起来你想要这个:

NSString *search = @"small widget";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ contains[cd] size AND %@ contains[cd] category", search, search];

搜索字符串将包含(或不包含)大小和类别,您应该询问搜索字符串中是否包含当前大小或类别。

您还可以拆分搜索字符串并修改谓词。你应该让他们找出表现更好的那个

NSString *search = @"small widget";
    NSArray *array = [search componentsSeparatedByString:@" "];
    NSMutableArray *subPredicates = [NSMutableArray array];
    for (NSString *q in array) {
        [subPredicates addObject:
         [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", q, q]];
    }
    NSCompoundPredicate *predicate = [[[NSCompoundPredicate alloc] initWithType:NSAndPredicateType
                                                                 subpredicates:subPredicates] autorelease];

答案 1 :(得分:-1)

对于Swift,您可以使用 propertiesToFetch

获取多个列
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "<YOUR ENTITY NAME>")
let predicate = NSPredicate(format: "<YOUR PREDICATE>")
fetchRequest.predicate = predicate
fetchRequest.resultType = .dictionaryResultType


// Here is where you can query multiple columns, you can add as much columns as you want and fetch them as an array of dictionaries
fetchRequest.propertiesToFetch = ["column1", "column2", "column3, "column4"]


let sort = NSSortDescriptor(key: "column1", ascending: false)
fetchRequest.sortDescriptors = [sort]