【Xcode 12】macOS SwiftUI App AppDelegateを作る

Xcode 12 は 「Life Cycle: SwiftUI App」と言う設定ができるようになりました。

Life Cycle 「SwiftUI App」

protocol App継承で下記のようなシンプルな構成になりました。そして、AppDelegate.swiftがなくなりました。

@main
struct プロジェクト名: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

AppDelegateが必要な場合は、下記のようなAppDelegateクラスを用意します。

import Foundation
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {

    }
    
    func applicationWillTerminate(_ aNotification: Notification) {
        
    }
}

struct プロジェクト名:App{}側に@NSApplicationDelegateAdaptor()を追記してやります。

@main
struct プロジェクト名: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Swift #selectorと@objc func

Swift #selectorと@objc func

Swiftを使っていると必ずSelector引数で渡すファンクションが出てきます。Selectorはstructなのですがここに@objc関数を渡す場合#selector()に包んで渡す必要があるようです。引数にわたす場合#selector(funcName(_:))こんな感じに関数を入れればいいのですが 渡された側はどのように処理をしているのか調べてみました。

class TObject: NSObject {
    override init() {
        super.init()
    }
    @objc func a(_ :Any) {
        print("function a")
    }
    func b(_ f:Selector){
        self.perform(f)
    }
}
let a1 = TObject()
a1.b(#selector(a1.a(_:)))

TObjectというオブジェクトを作成しa と bの関数を作っています。aの関数は@objcです。最後の2行で実行します。b()にaの関数を入れてb()の中のperform(f)でa()を実行しprint(“function a”)を呼んでいます。NSButtonのaction: Selector?もこのように実行されているのかな

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED