如果用户点击操作表,我想用不同的谓词刷新NSFetchedResultController。
以下是代码:
lazy var fetchResultController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "Debt")
let filterText:String?
let ascending:Bool?
if NSUserDefaults.standardUserDefaults().objectForKey("filterType")?.stringValue == "name" {
filterText = "name"
ascending = true
}
else
{
filterText = "date"
ascending = true
}
let sortDescriptor = NSSortDescriptor(key: filterText, ascending: ascending!)
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.sharedManager.managedObjectContext, sectionNameKeyPath: filterText, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
@IBAction func didTouchUpInsideFilterButton(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "Filter By:", message: "", preferredStyle: .ActionSheet)
let nameAction = UIAlertAction(title: "Name", style: .Default) { (UIAlertAction) -> Void in
NSUserDefaults.standardUserDefaults().setObject("name", forKey: "filterType")
do {
try self.fetchResultController.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.userInfo)")
}
};
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (UIAlertAction) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
};
alertController.addAction(nameAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
在调用try self.fetchResultController.performFetch()方法后的alertAction完成块中,不会再次调用fetchResultController来更新谓词。
请找到解决方案。
答案 0 :(得分:1)
fetchResultController声明之后的代码块用于属性初始化,并且只会在第一次使用该属性时运行一次。这意味着当调用didTouchUpInsideFilterButton时,设置谓词等的代码块将不会运行(除非对self.fetchResultController的引用是第一次使用fetchResultController,这似乎不太可能)。
当您想要更新它时,您需要在初始化程序之外显式更改fetchResultController。