我正在使用 NSFetchedResultsController 来填充 UITableView,我正在尝试添加一个类别过滤器,因此如果用户选择一个类别需要重新加载 UITableView 上的数据,这就是我想要的做。
var categoriaAtual : Int?
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
print("Already fetch")
return _fetchedResultsController!
} else {
print("New Fetch")
}
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
self.managedObjectContext = managedContext
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Frases", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "favorita", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchLimit = 20
if categoriaAtual != nil {
print("Categoria Atual \(categoriaAtual)")
fetchRequest.predicate = NSPredicate(format: "categoria = %d",categoriaAtual!)
fetchRequest.fetchLimit = 2
} else {
print("No predicate");
}
//
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func setarCategoria(cat: Int) {
categoriaAtual = cat
_fetchedResultsController = nil
self.tableView.reloadData()
}
现在我有一个名为 MenuTableView.swift 的滑出菜单,我这样调用:(我认为问题就在这里)
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let homeVC = storyboard.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeTableViewController
homeVC.setarCategoria(indexPath.row)
self.slideMenuController()?.closeLeft()
}
我确实得到打印说这是一个新的获取,但 TableView 根本没有改变。
最佳答案
instantiateViewControllerWithIdentifer 创建 viewController 的新实例(因此也是 fetchedResultsController 的新实例),这就是您获取“New Fetch”日志的方式,但原始 TableView 不会更改。您可能只需要为 MenuTableView 提供一个 HomeViewController 可以实现的委托(delegate)即可。
关于ios - Swift:使用 NSFetchedResultsController 应用谓词后重新加载 TableView 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34999325/