访问变量在不同的类 - Swift [英] Access variable in different class - Swift
问题描述
我有两个swift文件:
i got two swift files :
main.swift
和 view.swift c>
在main.swift 中有一个变量$ c>初始设置为
0
。
使用 IBACtion
我将变量
设置为 10
,一切正常。
With an IBACtion
I set that variable
to be 10
, and everything is ok.
但是,如果我尝试访问变量
从 view.swift ,使用 main()。getValue()
,我总是 0
而不是 10
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.
在 main中的方法 getValue()
swift 看起来像这样:
The method getValue()
in main.swift looks like this:
func getValue() -> Int {
return variable
}
编辑
以下是代码(意大利语翻译:D)
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
}
}
感谢提前
Alberto
Thanks in advance Alberto
推荐答案
Swift中的文件和classes之间有一个重要的区别。文件与类没有任何关系。您可以在一个文件中定义1000个类,或在1000个文件中定义1个类(使用扩展名)。数据保存在实例类中,而不是在文件本身中。
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.
现在问题。通过调用 Main()
,您将创建 Main
类的一个全新实例与您连接到Xib文件的实例无关。这就是为什么值作为默认值。
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.
您需要做的是找到一种方法来获取同一实例作为您Xib中的实例。如果不了解你的应用程序的更多架构,我很难提出这样的建议。
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.
一个想法是,你可以添加一个引用在 View
中使用IBOutlet在您的Xib中使用 Main
然后你可以简单地做 self.main.getValue()
,它会在正确的实例上被调用。
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.
这篇关于访问变量在不同的类 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!