LoginSignup
61

More than 5 years have passed since last update.

SwiftでNSNotificationを利用してクラス間の処理を連携する

Last updated at Posted at 2015-01-18

備忘録です

画面内で別クラスで定義している2つのVIEW(仮にAとBとします)があって、
A側がスクロールされると、B側のVIEWのデータを更新する、という処理を下記のように実装

参考にさせていただいたリンク
http://dev.classmethod.jp/references/ios-8-swift-nsnotification-userinfo/
http://qiita.com/_tid_/items/a650900c9f2b57f1a22e
//Objective-Cですがわかりやすい説明で助かりました
http://iphone-tora.sakura.ne.jp/nsnotificationcenter.html

swift
■通知を送る側

//NSNotificationのインスタンスを作成。["value":100]という辞書型のデータを持たせる
var n : NSNotification = NSNotification(name: "dummy", object: self, userInfo: ["value": 100])
//通知を送る
NSNotificationCenter.defaultCenter().postNotification(n)


■通知を受け取る側

//initなどでNSNotification登録
NSNotificationCenter.defaultCenter().addObserver(self, selector: "update:", name: "dummy", object: nil)

//関数で受け取った時のアクションを定義
func update(notification: NSNotification)  {
 if let userInfo = notification.userInfo {
   let result = userInfo["value"]! as Int
   println("受信した数値:\(result)")
  }
}

■わかっていないこと
・userInfoは辞書型である必要があるのかわからない(現状は辞書型)

====追記========
通知を受け取る側において、initでNSNotificationを登録した場合、
deinitでNSNotificationを開放しておかないと、画面遷移して戻ってきた時などに
エラーになりました。

swift
    deinit {
        println("deinit call")
        //イベントリスナーの削除
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

NSNotificationは後片付けが大事なのですね。

参考:
http://qiita.com/mo_to_44/items/dbc3446e0334c5e07547
http://www.hawk-a.com/exception_code/archives/1349
http://swift-salaryman.com/nsnotificationcenter.php

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
61