NSPredicate连接属性

6

我正在尝试弄清楚如何连接属性名称。我有一个县和一个区属性,我想像这样查询:

[NSPredicate predicateWithFormat:@"county + district contains[cd] %@",searchBar.text]

我遇到了“未实现SQL生成谓词错误”的问题,而且我不确定如何实现NSPredicate。

4个回答

8
这应该能让您了解如何进行更复杂的搜索。它将匹配“县区”,“区县”等查询。
    NSArray *searchTerms = [searchBar.text componentsSeparatedByString:@" "];
    NSString *predicateFormat = @"(county contains[cd] %@) OR (district contains[cd] %@)";
    NSPredicate *predicate;
    if ([searchTerms count] == 1) {
        NSString *term = [searchTerms objectAtIndex:0];
        predicate = [NSPredicate predicateWithFormat:predicateFormat, term, term];
    } else {
        NSMutableArray *subPredicates = [NSMutableArray array];
        for (NSString *term in searchTerms) {
            NSPredicate *p = [NSPredicate predicateWithFormat:predicateFormat, term, term];
            [subPredicates addObject:p];
        }
        predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
    }
    [fetchRequest setPredicate:predicate];

请参见 Cocoa Is My Girlfriend:在您的Core Data应用程序中添加类似iTunes的搜索功能,了解更多解释。


1
这并不等同。连接 "ABC" + "DEF" 会匹配 "CDE"。而你的解决方案则不会。我理解在 OP 的上下文中这可能不是问题,但在我的情况下就不同了。所以问题是:如何在匹配之前连接实体的两列? - Jean-Denis Muys
最终我添加了一个派生属性,计算出两个源属性的串联。然后我在该派生属性上有一个谓词。这会浪费我的CoreData数据库中的存储空间,但在我的情况下,这是可以接受的代价。我可能已经将其设置为瞬态属性,但我不确定您是否可以查询其中一个。(说实话,我甚至没有尝试过) - Jean-Denis Muys
@Jean-DenisMuys 当你从SQLite存储进行初始查询时是不行的:https://dev59.com/qXA65IYBdhLWcg3w7Taa#3553471(此外,在看到那个答案之前我也尝试过,但没有成功) - Jbryson

3

最终我把两个变量(区域+国家)合并成一个字段,并在该字段上执行查询。


也许提供一个代码片段让人们学习会更有用? - Monolo

1

我做了类似的事情,并得出结论,像 cekisakurek 一样,最好的方法是将字段连接成一个公共字段(对于名字和姓氏更为相关)。

- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

然后使用“contains [cd]”过滤此字段

[NSPredicate predicateWithFormat:@"fullName contains[cd] %@", self.searchBar.text];

0
[NSPredicate predicateWithFormat:@"county contains[cd] %@ AND district contains[cd] %@",searchBar.text,searchBar.text];

只需尝试上述代码行,它将对您有所帮助。


如果我正确理解了OP的意图,那将是一个“OR”运算符。 - Jean-Denis Muys
@Jean-DenisMuys在问题中指定了国家+地区,这就是我在这里使用AND的原因。 - Raj
1
好的。然而,这并没有回答原问题,“如何在谓词中连接属性名称?”,即使OP并不是确切地这个意思。 - Jean-Denis Muys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接