2013年8月16日 星期五

ios Observer Pattern 的 NSNotificationCenter 使用 用法


在Design Patterns 中的 Observer Pattern 主要目是用來解決一對多的物件之間的依附關係 ,只要物件狀態一有變動,就可以通知其他相依物件做跟更新的動作,舉個簡單的例子 Observer 就像是一個班級裡負責聯絡的窗口一樣,當班級內有人有訊息需要通知給所有人時,只要告訴這個聯絡窗口,之後就由聯絡窗口統一通知班級內的所有人,當然也包含發佈消息的這個人。在 Objective-C 裡我們並不需要真的去實作出 Observer Pattern,透過使用 NSNotificationCenter 也可以達到相同的效果。


在開始前

先做一個.h  and .m


例如 Constant.h  and .m

先建立一組字串方便以後的處理

.h如下
extern NSString *const FoodChangeNoti;

.m如下


NSString *const FoodChangeNoti = @"FoodChangeNoti";


接下來要用到的viewcontroller  記得要把


#import "Constant.h"  加進去




NSNotificationCenter 可分為三個部分

第一個部分是
註冊

step1


在viewcontroller中

@interface FoodDateViewController () 

{
//宣告一個

id notiObserver;

}

step2

在viewcontroller 的viewDidLoad加入創建


    __weak FoodDateViewController *selfController = self;

    notiObserver = [[NSNotificationCenter defaultCenter] addObserverForName:FoodChangeNoti object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [selfController updateUi];

    }];



-(void)updateUi
{
//在這裡面寫你要做的事情 例如更新畫面


}


第二個部分是
取消

step1

記得離開這個viewcontroller要把它釋放掉


-(void)dealloc
{
    if(notiObserver)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:notiObserver];
        notiObserver = nil;
    }
    

}


setp2

在viewcontroller viewDidLoad 創建前也做一次釋放的動作

    if(notiObserver)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:notiObserver];
        notiObserver = nil;
    }



第三個部分是
訊息通知

step1

發出通知


[[NSNotificationCenter defaultCenter] postNotificationName:FoodChangeNoti object:nil userInfo:nil];



參考文獻:http://furnacedigital.blogspot.tw/2011/09/observer-pattern-nsnotificationcenter.html

0 意見:

張貼留言