在 NSPredicate 之后填充 table 视图
Populate table view after NSPredicate
我有一个包含核心数据的搜索栏,但遇到了问题。
当我搜索某些内容时,NSPredicate 会在 playground 上显示结果,但我无法重新加载 table 视图,它们什么也没显示。
我想知道我是否可以使用此代码重新加载 table:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var person = people[indexPath.row]
if searchController.searchBar.text != "" {
person = filteredPeople[indexPath.row]
}
cell.textLabel?.text = person.value(forKeyPath: "name") as? String
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell
}
或者我需要创建一个 fetchResultsController。
filteredPeople是在fetchRequest:
之后获取的
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
let predicate = NSPredicate(format: "name contains[c] %@",searchController.searchBar.text!)
fetchRequest.predicate = predicate
do {
let filteredPeople = try! managedContext.fetch(fetchRequest) as! [Person]
for result in filteredPeople as [Person] {
print("\(result.name!)")
}
}
self.tableView.reloadData()
}
祝一切顺利。
这是一个常见的错误。
您正在使用 let
关键字声明一个 局部变量 ,它与数据源数组不是同一个对象。
删除let
filteredPeople = try! managedContext.fetch(fetchRequest) as! [Person]
我有一个包含核心数据的搜索栏,但遇到了问题。
当我搜索某些内容时,NSPredicate 会在 playground 上显示结果,但我无法重新加载 table 视图,它们什么也没显示。
我想知道我是否可以使用此代码重新加载 table:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var person = people[indexPath.row]
if searchController.searchBar.text != "" {
person = filteredPeople[indexPath.row]
}
cell.textLabel?.text = person.value(forKeyPath: "name") as? String
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell
}
或者我需要创建一个 fetchResultsController。
filteredPeople是在fetchRequest:
之后获取的let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
let predicate = NSPredicate(format: "name contains[c] %@",searchController.searchBar.text!)
fetchRequest.predicate = predicate
do {
let filteredPeople = try! managedContext.fetch(fetchRequest) as! [Person]
for result in filteredPeople as [Person] {
print("\(result.name!)")
}
}
self.tableView.reloadData()
}
祝一切顺利。
这是一个常见的错误。
您正在使用 let
关键字声明一个 局部变量 ,它与数据源数组不是同一个对象。
删除let
filteredPeople = try! managedContext.fetch(fetchRequest) as! [Person]