Joh*_*ths 3 macos xcode swift swift2
我正在尝试让代表使用 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")
}
}
Run Code Online (Sandbox Code Playgroud)
一切看起来都正确,但 testPrint 和 trySomething 从未被调用,添加了断点但没有任何反应。
任何想法我错过了什么?
开车带我绕弯...
因为你self.delegate是nil对的?所以你应该先分配一个对象。像这样尝试,这是我的AppDelegate.swiftCocoa 演示项目中的代码:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
一切正常,我可以看到打印的日志。请注意,就我而言,我viewDidLoad直接调用函数 - 只是为了向您展示委托模式的工作原理。Apple 不建议直接调用它。正确的方法是呈现视图控制器,并且viewDidLoad函数将由 OS X SDK API 调用。
| 归档时间: |
|
| 查看次数: |
1338 次 |
| 最近记录: |