Shared variable between two tabs for Xcode

南笙酒味 提交于 2019-12-14 02:24:32

问题


I have two view controllers that I am working on which both inherits from a Base view controller

  1. class A_ViewController: BaseViewController
  2. class B_ViewController: BaseViewController

Both of those VC interacts heavily with my firebase database. So I want a variable to keep track of all the downloaded items so those two VC can access it without the need to re-download the file again.

I tried to put a variable name in BaseViewController for the two A,B class to access

    var allPostsDownloaded:  [Post]!

So before A_VC downloads any data, it checks for this allPostsDownloaded variable and loads from it if the data exists. If it doesnt exist, I append to this variable. So when switching to B_VC, the same can be done and no data is re-downloaded when not required.

Reason I am not using segue or protocal to pass data around is that the two VC interacts quite heavly with my database. So it was alot cleaner to try and have a mutural data varaible to keep track of where things are.

However, the problem is that i

var allPostsDownloaded:  [Post]!

gets called whenever I switch between A and B VC (Which are tabs). This will cause the variable to be empty and de-initialised.

I guess I could use a global variable instead but that is not good practice? Could anyone please explain why it gets re-called when new tab shows up? And the best solution for this.


回答1:


as @avi mentioned create new singleton class, then you can pass and read easily. Below is an example

class PersistentData
{
    static let sharedInstance = PersistentData()

    // your global persistent variable
    var allPostsDownloaded = [Post]()
}

So in your controllers you can simple read and set as below

// read
print(PersistentData.sharedInstance.allPostsDownloaded)

// set new data. this just example, hence depends on your case
PersistentData.sharedInstance.allPostsDownloaded.append(newPost)
PersistentData.sharedInstance.allPostsDownloaded = posts

also keep in mind that if you want to read new value when switching between tabs, you can get the updated in viewDidAppear or viewWillAppear




回答2:


You can create a Singleton class with a instance variable and can save all downloaded data, and can access singleton class variable from any where of your project's classes.



来源:https://stackoverflow.com/questions/38474564/shared-variable-between-two-tabs-for-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!