[macOS]始めよう | Cocoa練習帳

[macOS]始めよう

macOSプログラミングがマイブームだ。手始めに、初期のヒレガス本を最新の開発環境で頭からやってみることにする。

新規プロジェクトを作成。macOSでCocoa Applicationを選択。

以前と異なるのは、以前は自分でアプリケーションのコントローラとなるクラスAppControllerを生成したが、最新の開発環境では、iOSと同様に、AppDelegateとViewControllerが生成済み。

以前ならAppDelegateを選択したと思うが、ViewControllerにコントローラの処理を追加。

AppDelegateは、こんな感じ。

import Cocoa
 
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }
 
    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}

ViewControllerに乱数生成のコードを追加。

import Cocoa
import GameplayKit
 
class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
 
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
    
    @IBOutlet var textField: NSTextField?
 
    @IBAction func generate(sender: NSButton) {
        let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: 99) + 1
        textField?.integerValue = randomNumber
    }
    
    @IBAction func seed(sender: NSButton) {
        textField?.stringValue = "Generator seeded"
    }
}
ソースコード 
関連情報 
【Cocoa練習帳】