我刚刚使用CoreData
创建了一个新项目,其中包含" Master-Detail Application
"模板。我使用Apple提供的代码,我刚刚在fetchController中添加了NSPrediate
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext)
fetchRequest.entity = entity
// Here the code i added <<<<<<<<
fetchRequest.predicate = NSPredicate(format: "year = %d", self.selectedYear)
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// 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: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// 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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
其中selected.Year
是一个简单的var
。我还添加了一个连接到IBAction
的UIButton,它将更改selectedYear
的值。
@IBAction func changeYear(sender: AnyObject) {
self.selectedYear = self.selectedYear + 1
self.tableView.reloadData()
}
(我记录了函数changeYear
并且它被调用了)
所以在那之后我调用self.tableView.reloadData()
来更新UITableView
,现在应根据新谓词获取不同的记录,但tableView
永远不会更新
(我试图记录委托方法,但从未被解雇)。
我错过了什么?
我还试图从tableView
开始IBOutlet
storyboard
并尝试拨打self.tv.reloadData()
,但仍然没有。
答案 0 :(得分:0)
获取的结果控制器不能以这种方式工作。您需要根据新谓词告诉它重新获取:
_fetchedResultsController = nil
self.tableView.reloadData()
另一种方法是更改FRC的获取请求的谓词并调用
self.fetchedResultsController.performFetch(&error)
然后没有必要用reloadData()
重新加载表,因为委托应该处理它。但我认为你完全取代了表的内容,所以上面的解决方案可能更容易,而且效率也很高。