macos 自定义main函数,CustomApplication、CustomAppDelegate

iOS/macOS - Customize the NSApplication/UIApplication

在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()
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值