Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...