简体   繁体   English

快速更改计算属性

[英]Changing computed property in swift

I'm having NSFetchedResultsController as lazy computed property. 我将NSFetchedResultsController作为惰性计算属性。 Based on a variable, sort descriptor is created. 基于变量,创建排序描述符。 Here's my code: 这是我的代码:

private var sortOption: Options = .none
fileprivate lazy var inspirationsResults: NSFetchedResultsController<Inspiration> = {
    // Create Fetch Request
    let fetchRequest: NSFetchRequest<Inspiration> = Inspiration.fetchRequest()

    // Configure Fetch Request
    //let optn = self.sortOption.rawValue
    switch (self.sortOption) {
    case .sortAscending:
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "inspirationName", ascending: true)]
    case .sortDescending:
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "inspirationName", ascending: false)]
    case .sortByAdding:
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
    case .sortByUpdated:
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
    case .showFilter:
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
    default:
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
    }
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: false)]
    fetchRequest.fetchBatchSize = 10
    // Create Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.shared.getContext(), sectionNameKeyPath: nil, cacheName: nil)

    // Configure Fetched Results Controller
    fetchedResultsController.delegate = self

    return fetchedResultsController
}()

When sortOption variable's value is changed, I want to recompute "inspirationsResults" variable and change the sort descriptor accordingly. 当sortOption变量的值更改时,我想重新计算“ inspirationsResults”变量并相应地更改排序描述符。 How to achieve it? 如何实现呢?

Put the code to compute the sort descriptor into the didSet observer of the sortOption property: 将用于计算排序描述符的代码放入sortOption属性的didSet观察器中:

private var sortOption: Options = .none {
    didSet {
        let sortDescriptor : NSSortDescriptor
        switch sortOption {
            case .sortAscending:
                sortDescriptor = NSSortDescriptor(key: "inspirationName", ascending: true)
            case .sortDescending:
                sortDescriptor = NSSortDescriptor(key: "inspirationName", ascending: false)
            default:
                sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
         }
         fetchedResultsController.fetchRequest.sortDescriptors = [sortDescriptor]
         do {
            try fetchedResultsController.performFetch()
            tableView.reloadData()
         } catch {
            print(error)
         }
    }
}

The default case covers all explicit cases which sort by timeStamp - false . default案例包括所有按timeStamp - false排序的显式案例。
After changing the sort descriptor you need to perform a new fetch and reload the table view. 更改排序描述符后,您需要执行新的访存并重新加载表视图。

And in the method to initialize the results controller simply write: 并在初始化结果控制器的方法中只需编写:

self.sortOption = .none

I believe that a property declared as lazy can't be changed once it's set. 我相信声明为惰性的属性一旦设置就无法更改。

You can create the same thing yourself using a property with a custom getter that returns a private property that's created if it's nil. 您可以使用带有自定义getter的属性来自己创建相同的事物,该属性将返回创建为null的私有属性。 Have the setter for sortOption set the private property to nil to force it to be recalculated. 让sortOption的setter将private属性设置为nil,以强制重新计算该属性。

If you change the declaration of inspirationsResults to be an implicitly unwrapped optional 如果更改的声明inspirationsResults是一个隐含展开可选

fileprivate lazy var inspirationsResults: NSFetchedResultsController<Inspiration>! = { ...

...then you can force it to reinitialize by setting its value to nil. ...然后您可以通过将其值设置为nil来强制其重新初始化。 As in, if you set inspirationsResults to nil, then the next time you access it, the initialization code runs again. 如,如果你设置inspirationsResults为零,那么下次访问它时,初始化代码再次运行。 Using an implicitly unwrapped optional is safe here as long as your initialization code never returns nil. 只要您的初始化代码从不返回nil,在这里使用隐式解包的可选是安全的。

You could then set inspirationResults to nil in the didSet observer for sortOption . 然后,您可以设置inspirationResults为零的didSet观察员sortOption The next time you use inspirationResults you'll get a new version with new sorting. 下次使用inspirationResults您将获得具有新排序的新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM