Home > OS >  Swift: How to hold on to tableView data during the lifecycle of the application?
Swift: How to hold on to tableView data during the lifecycle of the application?

Time:08-17

I have a tableView that I populate with data from my firestore database. Here is the code:

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        firebaseSource.firebaseDelegate = self
        if (!isUserSignedIn()) {
            navigateToLogin()
        } else {
            repository?.getAllDevices(email: (auth.currentUser?.email)!, completion: {(map: [String : Array<String>], names: Array<String>) -> Void in
                self.devicesMap = map
                self.deviceNames = names
                self.tableView.reloadData()
            })
        }
        self.registerTableViewCells()
        self.tableView.delegate = self
        self.tableView.dataSource = self
    }

I need to load the data into the tableView every time the viewController appears but I wonder if it isn't a good idea to call getAllDevices() on the database every time the user navigates away from and back to the viewController within the applications lifecycle.

Is there a way I can hold onto the data in the tableView and reload it without a database operation? I have considered trying to just pass the data around to the other viewControllers and then passing it back when I need to but I wonder if there might be a better way I haven't thought of.

CodePudding user response:

Its fine to query from a DB regularly, but if you are querying the same data very frequently and want to avoid unnecessary loading, a third option is to use a singleton to cache the data and only fetch if needed

e.g.

class SomeDataSingleton {
    public let shared = SomeDataSingleton()

    private someDataArray = []
    
    private init() {}


    public func fetchSomeDataIfNeeded(completion: @escaping ((Result<[], Error>))) {
        if someDataArray.count == 0 {
            completion(Result.success(someDataArray))
    
        } else {
    
            // database lookup, and callback
                someDataArray = dataBaseArray
                completion(Result.success(someDataArray))
        }
    }
}
  • Related