CoreData谓词获取包含数组中任何单词的每个句子 [英] CoreData Predicate get every sentence that contains any word in array

查看:85
本文介绍了CoreData谓词获取包含数组中任何单词的每个句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 4中,我有一个CoreData Sentence模型,该模型具有String属性 englishsentence。我也有一个单词数组,并希望获取所有 englishsentence属性包含数组中一个或多个单词的句子。

In Swift 4 I have a CoreData "Sentence" model that has a String attribute "englishsentence". I also have an array of "words" and would like to fetch all sentences for which the "englishsentence" attribute contains one or more of the words in the array.

var words = ["today", "yesterday", "tomorrow"]

此数组只是一个例子。

This array is just an example. It is supposed to change at runtime and can have any length.

在获取请求中,我试图做这样的事情:

and in the fetch request I am trying to do something like this:

let fetchRequest =
    NSFetchRequest<NSManagedObject>(entityName: "Sentence")
let predicate = NSPredicate(format: "ANY englishsentence CONTAINS ANY word IN %@", words)
    fetchRequest.predicate = predicate

我能够为包含一个特定单词的所有句子创建一个谓词。但是,除非我遍历单词数组并对每个单词提出新的获取请求,否则我无法使其与单词数组一起使用。但这似乎效率很低。

I am able to create a predicate for all sentences that contain one particular word. However, I cannot get it to work with an array of words unless of course I iterate through the words-array and make a new fetch request for every single word. But this seems awfully inefficient.

推荐答案

一种选择是创建一个复合谓词:

One option would be to create a "compound predicate:"

let words = ["today", "yesterday", "tomorrow"]

let predicates = words.map {
    NSPredicate(format: "englishsentence CONTAINS %@", $0)
}
let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)

另一个选择是与正则表达式匹配:

Another option is to match against a regular expression:

let regex = ".*(" + words.map {
    NSRegularExpression.escapedPattern(for: $0)
}.joined(separator: "|") + ").*"

let predicate = NSPredicate(format: "englishsentence MATCHES %@", regex)

要仅匹配整个单词,您可以添加单词边界模式 \b

To match only "whole words" you can add the word boundary pattern \b:

let regex = ".*\\b(" + words.map {
    NSRegularExpression.escapedPattern(for: $0)
}.joined(separator: "|") + ")\\b.*"

这篇关于CoreData谓词获取包含数组中任何单词的每个句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆