访问不同类中的变量 - Swift [英] Access variable in different class - Swift

查看:26
本文介绍了访问不同类中的变量 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 swift 文件:

i got two swift files :

main.swiftview.swift

在 main.swift 中,我有一个 variable (Int) 最初设置为 0.

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

使用 IBACtion 我将 variable 设置为 10,然后一切正常.

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

但是,如果我尝试通过 main().getValue() 之类的简单调用从 view.swift 访问该 variable,我总是 0 而不是 10 即使变量已经改变了它在 main.swift 中的值.

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.

ma​​in.swift 中的方法 getValue() 如下所示:

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

提前致谢阿尔贝托

推荐答案

Swift 中的文件"和类"之间有一个重要的区别.文件与类没有任何关系.您可以在一个文件中定义 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆