Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

methods - Access variable in different class - Swift

i got two swift files :

main.swift and view.swift

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

With an IBACtion I set that variable to be 10, and everything is ok.

However, if I try access that variable from view.swift, with a simple call like main().getValue(), i get always 0 and not 10 even if the variable has changed it's value in main.swift.

The method getValue() in main.swift looks like this:

func getValue() -> Int {
return variable
}

EDIT

Here is the code (Translated from Italian :D )

import Cocoa

class Main: NSObject {

    var variable: Int = 0

    func getValue() -> Int {
        return variable
    }

    @IBAction func updateVar(sender: AnyObject!) {
        variable = 10
    }
}

class View: NSView {
    override func drawRect(dirtyRect: NSRect) {
       println(Main().getValue()) //Returns always 0
    }
}

Thanks in advance Alberto

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...