今回は完全に自分用メモです。 背景もへったくれもなく、人に読んで頂くための記事でもなく、本当にふと思いついて試したことを忘れないうちにメモっておくために走り書いた感じです。 このへんを参考に、Swift から NSNotificationCenter を使って「通知」の仕組みを作ろうというお話。 Xcode 6 beta 3 で動作確認しています。 ちなみにSwift は言語仕様の破壊的な改訂がけっこうひんぱんに行われており、以下のコードは Xcode 6 beta 2 以前の処理系ではコンパイルエラーになります。 (※ちなみに、はてなブログは7月13日時点で Swift のシンタックスハイライトに対応していないため、暫定的にActionScriptモードで表示しています) // Xcode 6 beta 3 で動きます import Foundation // 監視をする人(通知を受ける
Notificationの使い方に関してはググればいくらでも出てくると思いますが、ここでは実戦向けに少しだけ掘り下げて説明出来ればと思います。 アプリケーション独自のNotification関連を定義するファイル アプリケーションのプレフィックス(大文字2文字)+Notificationという名前のファイルにNotification関連の定義をまとめておくと良いでしょう。 今回はSTNotification.hとSTNotification.mというファイルにまとめることにします。 Notification名の定義 SDKや他のライブラリの名前と重複しないようにNotification名をつける必要があります。アプリケーションのプレフィックス+Notification名+Notificationという命名規則にすると良いでしょう。 今回は以下のようなNotificationを定義します。
iOS 4からNSNotificationCenterに追加されたaddObserverForName:object:queue:usingBlock:メソッドを使うと、コールバックをブロックで指定することができるのでとても便利です。しかし、従来のセレクタ指定型のaddObserver:selector:name:object:のブロック版、という認識で使ってはいけません。 addObserver:とremoveObserver:のペア 例えば、ビューコントローラが全面に出ているときは通知を受け取りたいが、popされたり他のビューコントローラが上にきた時は通知を受け取りたくない、というようなパターンはNSNotificationCenterを使うとスマートに実装できます。 ビューコントローラのviewDidAppearでaddObserver:…を使って自身をオブザーバーとして登録して、v
Please note: this article is part of the older "Objective-C era" on Cocoa with Love. I don't keep these articles up-to-date; please be wary of broken code or potentially out-of-date information. Read "A new era for Cocoa with Love" for more. Here are five different ways to implement the Observer design pattern (sometimes called Broadcaster/Listener, Publish/Subscribe or Notifications) in Objective
We’ve discussed the importance of how events are communicated in APIs previously in our article on Key-Value Observing. This week, we’ll expand our look at the available options, with NSNotificationCenter & NSNotification. NSNotificationCenter provides a centralized hub through which any part of an application may notify and be notified of changes from any other part of the application. Observers
Notifications and KVO serve similar functions, but with different trade-offs. Notifications are easy to understand. KVO is... challenging... to understand (at least to understand how to use it well). Notifications require modification to the observed code. The observed must explicitly generate every notification it offers. KVO is transparent to the observed code as long as the observed code confor
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く