天天看點

IOS中通知中心(NSNotificationCenter)的使用總結

這個類可以了解為一個消息對象,其中有三個成員變量。

這個成員變量是這個消息對象的唯一辨別,用于辨識消息對象。

@property (readonly, copy) nsstring *name;

這個成員變量定義一個對象,可以了解為針對某一個對象的消息。

@property (readonly, retain) id object;

這個成員變量是一個字典,可以用其來進行傳值。

@property (readonly, copy) nsdictionary *userinfo;

nsnotification的初始化方法:

- (instancetype)initwithname:(nsstring *)name object:(id)object userinfo:(nsdictionary *)userinfo;

+ (instancetype)notificationwithname:(nsstring *)aname object:(id)anobject;

+ (instancetype)notificationwithname:(nsstring *)aname object:(id)anobject userinfo:(nsdictionary *)auserinfo;

注意:官方文檔有明确的說明,不可以使用init進行初始化

這個類是一個通知中心,使用單例設計,每個應用程式都會有一個預設的通知中心。用于排程通知的發送的接受。

添加一個觀察者,可以為它指定一個方法,名字和對象。接受到通知時,執行方法。

- (void)addobserver:(id)observer selector:(sel)aselector name:(nsstring *)aname object:(id)anobject;

發送通知消息的方法

- (void)postnotification:(nsnotification *)notification;

- (void)postnotificationname:(nsstring *)aname object:(id)anobject;

- (void)postnotificationname:(nsstring *)aname object:(id)anobject userinfo:(nsdictionary *)auserinfo;

移除觀察者的方法

- (void)removeobserver:(id)observer;

- (void)removeobserver:(id)observer name:(nsstring *)aname object:(id)anobject;

幾點注意:

1、如果發送的通知指定了object對象,那麼觀察者接收的通知設定的object對象與其一樣,才會接收到通知,但是接收通知如果将這個參數設定為了nil,則會接收一切通知。

2、觀察者的sel函數指針可以有一個參數,參數就是發送的死奧西對象本身,可以通過這個參數取到消息對象的userinfo,實作傳值。

首先,我們在需要接收通知的地方注冊觀察者,比如:

<a href="http://my.oschina.net/u/2340880/blog/406163#">?</a>

1

2

3

4

<code>    </code><code>//擷取通知中心單例對象</code>

<code>    </code><code>nsnotificationcenter * center = [nsnotificationcenter defaultcenter];</code>

<code>    </code><code>//添加目前類對象為一個觀察者,name和object設定為nil,表示接收一切通知</code>

<code>    </code><code>[center addobserver:self selector:@selector(notice:) name:@</code><code>"123"</code> <code>object:nil];</code>

之後,在我們需要時發送通知消息

<code>    </code><code>//建立一個消息對象</code>

<code>    </code><code>nsnotification * notice = [nsnotification notificationwithname:@</code><code>"123"</code> <code>object:nil userinfo:@{@</code><code>"1"</code><code>:@</code><code>"123"</code><code>}];</code>

<code>    </code><code>//發送消息</code>

<code>       </code><code>[[nsnotificationcenter defaultcenter]postnotification:notice];</code>

我們可以在回調的函數中取到userinfo内容,如下:

<code>-(</code><code>void</code><code>)notice:(id)sender{</code>

<code>    </code><code>nslog(@</code><code>"%@"</code><code>,sender);</code>

<code>}</code>

列印結果如下:

IOS中通知中心(NSNotificationCenter)的使用總結

繼續閱讀