Swift 如何将NSSet的内容追加到[NSManagedObject]?

Swift 如何将NSSet的内容追加到[NSManagedObject]?,swift,core-data,entity-relationship,nsmanagedobject,nsset,Swift,Core Data,Entity Relationship,Nsmanagedobject,Nsset,我的代码 isFiltering = true let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let words = textInSearchField.components(separatedBy: " ") for word in words{ if (word).co

我的代码

isFiltering = true
  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)
    let orPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.or, subpredicates: [firstNamePredicate, lastNamePredicate, idPredicate])

    clientsEntity.predicate = orPredicate
    clientResults = try! context.fetch(clientsEntity) as! [NSManagedObject]

    let sort:NSSortDescriptor = NSSortDescriptor(key:"dateSorted", ascending: false)

    for (index, ob) in clientResults.enumerated(){

      let relationship = ob.value(forKey: "assessed_by") as! NSSet
      let array = relationship.sortedArray(using: [sort]) as! [NSManagedObject]


      for item in array.enumerated() {
        results.append(item.element)
        print(results)
      }
    }
我的数据模型:

我正在使用一个tableView来显示我的数据,这非常有效,现在我已经实现了一个过滤功能,允许用户使用NSCompoundPredicate根据客户的名字、姓氏、id等进行搜索

然后,我使用NSSortDescriptor按日期对生成的[NSManagedObject]进行排序,我的目标是设置clientResults变量以包含NSSet的排序内容。我的print语句只输出results变量中有一个评估,而实际上NSSet包含其中两个nsmanagedObject

let sort:NSSortDescriptor = NSSortDescriptor(key:"dateSorted", ascending: false)

    for (index, ob) in clientResults.enumerated(){

      let relationship = ob.value(forKey: "assessed_by") as! NSSet
      let array = relationship.sortedArray(using: [sort]) as! [NSManagedObject]

      // MARK - I enumerate the contents of the sorted array.

      for item in array.enumerated() {
        results.append(item.element)
        print(results)
      }
    }
将NSSet的内容分配给[NSManagedObject]类型的变量的最佳做法是什么


谢谢。

如果您知道
NSSet
中的元素属于
NSManagedObject
类型,为什么不这样做呢

let managedObjectsArray = set.allObjects
或者,如果要确保其类型正确,可以执行以下操作:

if let managedObjectsArray = set.allObjects as? [NSManagedObject] {
    //do what you want with [NSManagedObject] array
}