首页 文章

什么是使用包含单词的谓词

提问于
浏览
1

我需要使用哪个谓词来自Core Data数组返回的对象:

  • 第一个对象必须完全匹配;

  • 其他对象必须包含特定的单词;

例如:我有实体Man(firstName:String,lastName:String) . 让我们说,我在核心数据中有这些对象:1)Man(firstName:“John”,secondName:“Alexandrov”),2)Man(firstName:“Alex”,secondName:“Kombarov”),3)Man(firstName) :“Felps”,secondName:“Alexan”) .

并且在返回的arr中我想看到[Man(firstName:“Alex”,secondName:“Kombarov”),Man(firstName:“Felps”,secondName:“Alexan”),Man(firstName:“John”,secondName:“亚历山德罗夫“)]

我怎么能做到这一点?

1 回答

  • 2

    你可以使用 NSCompoundPredicate .

    首先,你要为 firstName 创建一个谓词 . 这个是严格的,所以你要使用 == 搜索匹配:

    let firstNamePredicate = NSPredicate(format: "%K == %@", argumentArray: [#keyPath(Man.firstName), "alex"])
    

    然后,您将为 lastName 创建谓词 . 这个不太严格,所以你要使用 CONTAINS

    let lastNamePredicate = NSPredicate(format: "%K CONTAINS[c] %@", argumentArray: [#keyPath(Man.lastName), "alex"])
    

    然后,您将使用 orPredicateWithSubpredicates 签名创建NSCompoundPredicate .

    let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [firstNamePredicate, lastNamePredicate])
    

    从那里,您可以创建 NSFetchRequest 并将 compoundPredicate 指定为 fetchRequest 的谓词 .

    如果要对结果进行排序,可以在 NSFetchRequest 中添加一个或多个 NSSortDescriptor

    let sortByLastName = NSSortDescriptor(key: #keyPath(Man.lastName), ascending: true)
    let sortByFirstName = NSSortDescriptor(key: #keyPath(Man.firstName), ascending: true)
    request.sortDescriptors = [sortByLastName, sortByFirstName]
    

    然后,你做了获取:

    let request: NSFetchRequest = Man.fetchRequest()
    request.predicate = compoundPredicate
    
    var results: [Man] = []
    
    do {
      results = try context.fetch(request)
    } catch {
      print("Something went horribly wrong!")
    }
    

    这是 NSPredicate 的链接 NSPredicate

相关问题