– OC项目中自定义 application 类
macOS
- Step 1: 创建自己的类:CustomApplication
- Step 2: 更改info.plist 文件中 Principal class 配置的类名为 CustomApplication :
iOS
- Step 1: 创建自己的类:CustomApplication
- Step 2: main 方法中传入自定义类的名称:
– swift 项目中自定义 application 类
macOS
- Step 1: 创建自己的类:ACDHubApplication
@objc(ACDHubApplication) // 必须加上这句,否则运行报错:Unable to find class: MyApplication, exiting
class ACDHubApplication: NSApplication {
override func run() {
super.run()
}
}
- Step 2: 更改info.plist 文件中 Principal class 配置的类名为 ACDHubApplication (下图蓝色框)
- Step 3: 如果有Main.storyboard, 将其中的Application 的object的class 改为 ACDHubApplication (注:这一步我测试发现不做也没问题,不过还是改了好,可能我暂时没发现问题)
macos 自定义main函数,CustomApplication、CustomAppDelegate (Swift)
在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()
}
}