gpt4 book ai didi

ios - 在 Swift 中刷新 NSFetchedResultController

转载 作者:行者123 更新时间:2023-11-29 01:09:02 25 4
gpt4 key购买 nike

如果用户点击操作表,我想用不同的谓词刷新 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 完成 block 中,不会再次调用 fetchResultController 来更新谓词。

请找到解决方案。

最佳答案

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com