Objective-CからSwiftへの変換メモ その2

通知センター(Swift3.0以降)では、登録(addObserver)時の書き方がビックリなのでメモっておく。

Objective-Cだと

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

// Add observer for notification center
[notificationCenter addObserver:self
                       selector:@selector(didSendGameInfo:)
                           name:@"didSendGameInfo"
                         object:nil];

Swiftだと

let notificationCenter = NotificationCenter.default

// Add observer for notification center
notificationCenter.addObserver(self,
                      selector: #selector(self.didSendGameInfo),
                          name: NSNotification.Name(rawValue: "didSendGameInfo"),
                        object: nil)

selectorとnameが自動変換できなかった。しかもselectorで呼んでいるメソッドには@objcがいると言うおまけ付き。

加えてuserInfoの使い方に注意が要る。(型が<AnyHashable, Any>のため)

var userInfo:Dictionary<AnyHashable, Any> = [:]  // ややこしいがこれはクラス内で共通に使う変数

@objc func didSendGameInfo(notification: Notification) {
     self.userInfo = notification.userInfo!          // セレクタで受け取って
}

func windowShouldClose(sender: AnyObject) -> Bool {
    let theCommand = self.userInfo["theCommand"] as! String  // 使うときにキャストする
}

少しづつ、型にうるさい言語だと言う気はしてきた。

この投稿へのコメント

コメントはありません。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

この投稿へのトラックバック

トラックバックはありません。

トラックバック URL