在XCode中创建一个新的 Cocoa项目给我一个AppDelegate.swift文件,如下所示:
import Cocoa
@NSApplicationMain // Xcode 12 创建的是 @main
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
}
The @NSApplicationMain attribute is documented here
NSApplicationMain
Apply this attribute to a class to indicate that it is the application delegate. Using this attribute is equivalent to calling the NSApplicationMain(_:_: ) function.
If you do not use this attribute, supply a main.swift file with code at the top level that calls the NSApplicationMain(_:_: ) function as follows:
文档中的说明不起作用:AppDelegate类从未实例化.在this answer,vadian中建议main.swift的以下内容,它比文档中的代码更好用:
import Cocoa
// - 可以使用自定义的 appDelegate
let appDelegate = CustomAppDelegate()
//NSApplication.shared().delegate = appDelegate
// - 可以使用自定义的 CustomApplication
CustomApplication.shared.delegate = appDelegate // 猜测,调用一次 shared 后,全局就会产生一个NSApplication对象
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
CustomAppDelegate:
import Cocoa
// 此处无 @...
// @NSApplicationMain // Xcode 12 创建的是 @main
class CustomAppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationWillBecomeActive(_ notification: Notification) {
print("Victor-Debug: applicationWillBecomeActive")
}
func applicationDidBecomeActive(_ notification: Notification) {
print("Victor-Debug: applicationDidBecomeActive")
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
print("Victor-Debug: applicationDidFinishLaunching")
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
print("Victor-Debug: applicationWillTerminate")
}
}
CustomApplication:
// 必须加上这句,否则运行报错:Unable to find class: CustomApplication, exiting
// 或者 删除 Info.plist 中的Principal class, 不建议.
@objc(CustomApplication)
class CustomApplication: NSApplication {
override func run() {
print("Victor-Debug: CustomApplication::run")
super.run()
}
}