Swift 核心数据-通过属性获取和筛选一对多关系

Swift 核心数据-通过属性获取和筛选一对多关系,swift,core-data,filter,nspredicate,nsmanagedobject,Swift,Core Data,Filter,Nspredicate,Nsmanagedobject,我的数据模型 一个客户可以有多个评估,但一个评估只能有一个客户作为反向关系。我的目标是获取客户拥有的所有评估,并根据初始客户的“firstName”属性进行筛选 我的过滤功能: func filterData(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let words = text

我的数据模型

一个客户可以有多个评估,但一个评估只能有一个客户作为反向关系。我的目标是获取客户拥有的所有评估,并根据初始客户的“firstName”属性进行筛选

我的过滤功能:

  func filterData(){

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let words = textInSearchField.components(separatedBy: " ")

for word in words{

  if (word).count == 0{
    continue
  }

  let firstNamePredicate = NSPredicate(format: "firstName contains[c] %@", word)
  let lastNamePredicate = NSPredicate(format: "lastName contains[c] %@", word)
  let idPredicate = NSPredicate(format: "id contains[c] %@", word)

  // I am using a Compound Predicate so that I can filter by first name, last name but also the id property.
  let orPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.or, subpredicates: [firstNamePredicate, lastNamePredicate, idPredicate])

  clientsEntity.predicate = orPredicate

  // results is an array of type [NSManagedObject], I am using the compound predicate I created above to fetch specific clients. 
  results = try! context.fetch(clientsEntity) as! [NSManagedObject]

 }
}
我基本上是想通过名字、姓氏或ID获得客户的所有评估。NSPredicate是最好的方法吗


谢谢。

使用此选项,您可以从核心数据中获取所有筛选数据。取下客户机,并通过获得评估结果。