【问题标题】:Refresh NSFetchedResultController in Swift在 Swift 中刷新 NSFetchedResultController
【发布时间】:2016-03-14 11:46:32
【问题描述】:

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

请找到解决办法。

【问题讨论】:

    标签: ios iphone swift core-data nsfetchedresultscontroller


    【解决方案1】:

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

    当你想更新它时,你需要在初始化器之外显式地改变 fetchResultController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2021-09-04
      • 2016-12-26
      • 1970-01-01
      • 2014-08-19
      • 2017-01-13
      相关资源
      最近更新 更多