如果用户单击“操作表”,我想用不同的谓词刷新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来更新谓词。

请找到解决方案。

最佳答案

fetchResultController声明之后的代码块用于属性初始化,仅在第一次使用该属性时才运行一次。这意味着,在调用didTouchUpInsideFilterButton时,将不会运行设置谓词等的那部分代码(除非是第一次使用fetchResultController来引用self.fetchResultController,这似乎不太可能)。

当您想要更新fetchResultController时,需要在初始化程序之外对其进行显式更改。

关于ios - 在Swift中刷新NSFetchedResultsController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35986672/

10-13 02:47