Xcode OSX中的代表与Swift
我正在尝试让学员使用Swift为OSX应用程序工作Xcode OSX中的代表与Swift,xcode,swift,macos,swift2,Xcode,Swift,Macos,Swift2,我正在尝试让学员使用Swift为OSX应用程序工作 import Cocoa class loginViewController: NSViewController { weak var delegate: recordViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Do view setup here. delegate?.trySo
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从未被调用,添加了断点,但什么也没发生
你知道我错过了什么吗
让我转过弯来…因为你的
自我委托是零对吗?因此,您应该首先指定一个对象。
这样试试看,下面是我的AppDelegate.swift
Cocoa演示项目的代码:
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
函数——只是为了向您展示委托模式的工作原理。
苹果不建议直接给它打电话。正确的方法是显示视图控制器,OS X SDK API将调用viewDidLoad
函数。最后两行是出于绝望,我找到了一个建议这样做的示例,但至少是:委托?.trySomething()应该有firedYou具有弱变量委托:recordViewControllerDelegate?
可选属性。您应该初始化它并将委托对象分配给它,委托对象将负责testPrint()
。谢谢,尝试添加self.delegate=recordViewController(),但仍然没有成功。我是否缺少一个库?谢谢,通过删除var委托:recordViewController上的薄弱环节,最终使它正常工作了?并且self.delegate=recordViewController()很高兴能帮忙,很高兴编码!如果我没有弄错的话,设置委托模式需要两个协议。请看这里:如果你想要一个示例,请问:D。当然,如果可以的话?我现在不在电脑旁,所以如果没有其他人在,我会在大约一小时后发布一个。谢谢,非常感谢。所以你不需要示例,对吗?