我的代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="Select">
<option value="" disabled='' selected=''>Select a City</option>
<option value="NewYork">New York</option>
<option value="Shanghai">Shanghai</option>
<option value="London">London</option>
</select>
<div id="div1">
<h2>Please select city from top</h2>
</div>
我的数据模型:
我正在使用tableView来显示我的数据,效果很好,现在我实现了一个过滤器功能,该功能使用户可以使用NSCompoundPredicate根据客户端的名字,姓氏,ID等进行搜索。
然后我使用NSSortDescriptor按日期对结果 [NSManagedObject] 进行排序,我的目标是设置 clientResults 变量以包含NSSet的已排序内容。我的打印语句仅输出结果变量内部有一个评估,而实际上NSSet包含其中两个NSManagedObjects。
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)
}
}
将NSSet的内容分配给类型为[NSManagedObject]的变量的最佳实践是什么?
谢谢。
答案 0 :(得分:1)
如果您知道NSSet
中的元素属于NSManagedObject
类型,为什么不这样做
let managedObjectsArray = set.allObjects
或者如果您要确保其类型正确,可以执行以下操作:
if let managedObjectsArray = set.allObjects as? [NSManagedObject] {
//do what you want with [NSManagedObject] array
}