【发布时间】:2018-04-23 15:48:30
【问题描述】:
在 Swift 中尝试一些事情。我正在尝试理顺一些对我来说似乎很混乱的事情——主要是关于我如何处理变量并在项目中引用它们。
我要做的是保持 ViewController 中定义的变量(基于结构)从应用程序中的各种其他函数访问和更新。
所以,这里是我所拥有的代码的简要概述。实际上,我编写了一个较小的应用程序来测试我的想法,然后再将它们应用到更复杂的东西上。
我从 XCode 开始,使用 Mac OSX 的基于 Swift 文档的应用程序。
在 ViewController.swift 我有:
import Cocoa
class ViewController: NSViewController {
var myText = "Hello, some text"
@IBOutlet weak var textView1: NSTextField!
@IBAction func Button1(_ sender: Any) {
myText = "This is button 1 clicked"
myText = setText( thisText: &myText )
textView1.stringValue = myText
}
@IBAction func Button2(_ sender: Any) {
print("Button 2")
myText = "This is button 2 clicked"
textView1.stringValue = myText
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textView1.stringValue = myText
}
override func viewDidAppear() {
let document = self.view.window?.windowController?.document as! Document
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
在 SetText.swift 中,我有这个:
import Foundation
func setText( thisText: inout String) -> String {
thisText = "Function"
return thisText
}
我喜欢将变量发送到 Set Text 函数然后返回它的想法,但仔细考虑它让我觉得实际上这可能会像众所周知的一碗意大利面条,其中包含函数调用函数并且谁知道还有什么。所以我在想这样的事情可能更有意义:
import Foundation
func setText( thisText: inout String) {
let vc = ViewController()
// Read the variable from View Controller
var myTextHere = vc.myText
myTextHere = myTextHere + " More text"
// Set the variable in ViewController here
vc.myText = myTextHere
}
根据我对这个主题的阅读,如果我调用 ViewController(),它将创建一个新的视图实例(是正确的,还是我误读了?)。这已经发生了,所以我需要引用调用 setText 函数的 ViewController,或者更确切地说,它拥有那个特定的代码实例。在考虑基于文档的应用程序时,我显然希望将 myText 的所有实例与每个文档的 ViewController 一起保留。
我的目标是创建一些更复杂的东西,使用基于 Struct 的变量将所有内容组合在一起。所以:
myCard.image // holds a bitmap image
myCard.size // holds the size of the image
等等。能够以 ViewController().myCard 的形式访问它以进行读写是我认为我需要做的。
我不想做的是使用全局变量。
谢谢。
【问题讨论】:
-
尝试搜索已经回答的类似问题。这里有无数这样的人。
-
你应该看看 Adopting Cocoa Design Patterns 更具体的singleton。 developer.apple.com/library/content/documentation/Swift/…
标签: swift macos class variables