如何使用公共NSURL变量

时间:2014-11-10 22:56:48

标签: macos swift

我是Swift和Xcode的新手, 我想创建一个新的公共NSURL变量,我希望稍后在我的代码中使用它来赋予它值并在以后使用该值。如下所示:

class AddUrlViewController: NSViewController {

@IBOutlet weak var txtPath: NSTextField!

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  @IBAction func btnFileDialog(sender: NSButton) {
    let myFiledialog:NSOpenPanel = NSOpenPanel()
        myFiledialog.canChooseDirectories = true
        myFiledialog.canChooseFiles = false

    var returnCode:NSInteger = myFiledialog.runModal()

    if (returnCode == NSOKButton) {
        /////////// Use it here
        var directoryUrl = myFiledialog.URL?.absoluteURL
    }
  }

  @IBAction func btnStart(sender: NSButton) {
    //////////// Use it here
  }
}

我应该如何以最佳方式实现这一目标?

1 个答案:

答案 0 :(得分:0)

只需将变量定义为函数范围之外的属性 -

class AddUrlViewController: NSViewController {

@IBOutlet weak var txtPath: NSTextField!
var directoryUrl:NSURL?

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  @IBAction func btnFileDialog(sender: NSButton) {
    let myFiledialog:NSOpenPanel = NSOpenPanel()
        myFiledialog.canChooseDirectories = true
        myFiledialog.canChooseFiles = false

    var returnCode:NSInteger = myFiledialog.runModal()

    if (returnCode == NSOKButton) {
        /////////// Use it here
        self.directoryUrl = myFiledialog.URL?.absoluteURL
    }
  }

  @IBAction func btnStart(sender: NSButton) {
    if (self.directoryUrl != nil) {

    //////////// Use it here
    }
  }
}