swift2 OSX中的代理与Swift

s5a0g9ez  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(170)

我正在尝试让代表们使用Swift为OSX应用程序工作。

import Cocoa

class loginViewController: NSViewController {
    weak var delegate: recordViewControllerDelegate?

    override func viewDidLoad() {
      super.viewDidLoad()
      // Do view setup here.
      delegate?.trySomething()
      self.delegate?.trySomething()
      self.delegate?.testPrint("hello, is it me your looking for")
    }
}

protocol recordViewControllerDelegate: class {
  func testPrint(val: String)
  func trySomething()
}

class recordViewController: NSViewController, recordViewControllerDelegate {

  func testPrint(val: String) {
    print(val)
  }

  func trySomething() {
    print("aaa")
  }
}

一切看起来都很正常,但testPrint & trySomething从未被调用,添加了断点,但什么都没有发生。
你知道我错过了什么吗?
把我逼得弯曲。

4bbkushb

4bbkushb1#

因为你的self.delegatenil,所以你应该先分配一个对象。试着这样做,这是我的AppDelegate.swift可可演示项目的代码:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        //This is not a good practice to call viewDidLoad directly
        //Its just a demonstration of quick way to call `recordViewControllerDelegate` protocol functions
        let vc = loginViewController()
        vc.viewDidLoad()
    }
}

//MARK:- login VC
class loginViewController: NSViewController {
    weak var delegate: recordViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        let recVC = recordViewController()
        self.delegate = recVC

        delegate?.trySomething()
        self.delegate?.trySomething()
        self.delegate?.testPrint("hello, is it me your looking for")
    }
}

protocol recordViewControllerDelegate: class {
    func testPrint(val: String)
    func trySomething()
}

class recordViewController: NSViewController, recordViewControllerDelegate {

    func testPrint(val: String) {
        print(val)
    }

    func trySomething() {
        print("aaa")
    }
}

一切正常,我可以看到打印的日志。请注意,在我的例子中,我直接调用viewDidLoad函数-只是为了向你展示委托模式是如何工作的。苹果不建议直接调用它。正确的方法是提供视图控制器,viewDidLoad函数将由OS X SDK API调用。

相关问题