我的代码
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 的已排序内容。我的打印语句仅输出结果变量中有一个评估,而实际上 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] 的变量的最佳做法是什么?
谢谢。
最佳答案
如果您知道 NSSet
中的元素属于 NSManagedObject
类型,为什么不这样做
let managedObjectsArray = set.allObjects
或者如果你想确保它是正确的类型,你可以这样做:
if let managedObjectsArray = set.allObjects as? [NSManagedObject] {
//do what you want with [NSManagedObject] array
}
关于swift - 如何将 NSSet 的内容附加到 [NSManagedObject]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52117383/