Access variable in different class - Swift

后端 未结 2 936
离开以前
离开以前 2020-11-29 21:51

i got two swift files :

main.swift and view.swift

In main.swift i have a variable (Int) initially set

相关标签:
2条回答
  • 2020-11-29 22:15

    I have solved this by creating a generic main class which is accessible to all views. Create an empty swift file, name it 'global.swift' and include it in your project:

    global.swift:

    class Main {
      var name:String
      init(name:String) {
        self.name = name
      }
    }
    var mainInstance = Main(name:"My Global Class")
    

    You can now access this mainInstance from all your view controllers and the name will always be "My Global Class". Example from a viewController:

    viewController:

    override func viewDidLoad() {
            super.viewDidLoad()
            println("global class is " + mainInstance.name)
        }
    
    0 讨论(0)
  • 2020-11-29 22:28

    There is an important distinction to be made between "files" in Swift and "classes". Files do not have anything to do with classes. You can define 1000 classes in one file or 1 class in 1000 files (using extensions). Data is held in instances of classes, not in files themselves.

    So now to the problem. By calling Main() you are creating a completely new instance of the Main class that has nothing to do with the instance that you have hooked up to your Xib file. That is why the value comes out as the default.

    What you need to do, is find a way to get a reference to the same instance as the one in your Xib. Without knowing more of the architecture of your app, it is hard for me to make a suggestion as to do that.

    One thought, is that you can add a reference to your Main instance in your Xib using an IBOutlet in your View. Then you can simply do self.main.getValue() and it will be called on the correct instance.

    0 讨论(0)
提交回复
热议问题