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

问题描述 投票:0回答:1

我的守则

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)
      }
    }

我的数据模型:

enter image description here

我使用tableView来显示我的数据,这很好用,现在我已经实现了一个过滤功能,允许用户使用NSCompoundPredicate基于客户端的名字,姓氏,ID等进行搜索。

然后我使用NSSortDescriptor按日期对结果[NSManagedObject]进行排序,我的目标是将我的clientResults变量设置为包含NSSet的SORTED内容。我的print语句只输出结果变量中有一个Assessment,而实际上NSSet包含两个NSManagedObjects。

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]类型的变量的最佳做法是什么?

谢谢。

swift core-data entity-relationship nsmanagedobject nsset
1个回答
1
投票

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

let managedObjectsArray = set.allObjects

或者如果你想确保它的类型正确,你可以这样做:

if let managedObjectsArray = set.allObjects as? [NSManagedObject] {
    //do what you want with [NSManagedObject] array
}       
© www.soinside.com 2019 - 2024. All rights reserved.