1. 程式人生 > >NSNotificationCenter訊息通訊機制介紹(KVO)

NSNotificationCenter訊息通訊機制介紹(KVO)

作用:NSNotificationCenter是專門供程式中不同類間的訊息通訊而設定的.

註冊通知:即要在什麼地方接受訊息

               [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(mytest:) name:@" mytest" object:nil]

      引數介紹:

          addObserver: 觀察者,即在什麼地方接收通知;

        selector: 收到通知後呼叫何種方法;

        name: 通知的名字,也是通知的唯一標示,編譯器就通過這個找到通知的。

傳送通知:呼叫觀察者處的方法。

           [[NSNotificationCenter defaultCenter] postNotificationName:@"mytest" object:searchFriendArray];

          引數:

         postNotificationName:通知的名字,也是通知的唯一標示,編譯器就通過這個找到通知的。

                 object:傳遞的引數

註冊方法的寫法:

- (void) mytest:(NSNotification*) notification

{

   id obj = [notification object];//獲取到傳遞的物件

附:註冊鍵盤升啟關閉訊息
  1. //鍵盤升起 
  2. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  3. //鍵盤降下
  4. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

看一個程式,裡面viewDidLoad中有
    NSNotificationCenter  *center = [NSNotificationCenter defaultCenter];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"saveMessage" object:nil];
    [center addObserver:self selector:@selector(saveMessage) name:@"saveMessage" object:nil];

不明白為什麼先去掉註冊者,然後又新增?不是同一個observer嗎?

訊息傳送機構:舉例說明


在有需要的類中,傳送訊息
//傳送訊息出去,這裡的物件是一個數組:saveImageArray
[[NSNotificationCenter defaultCenter] postNotificationName:@"postData" object:saveImageArray];

所有親朋好友給我給包(傳送訊息),,,



    



//註冊一個observer來響應訊息的傳送
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(PostImage:)//接收訊息方法
                                                 name:@"postData"//訊息識別名稱
                                               object:nil];
                                               
舉個例子,過年了,準備一個大的錢包(註冊一個OBserver),嘿嘿,,,,                                               
            
                
                                   
                        
//實現方法            
-(void)PostImage:(NSArray *)array
{
    //接收傳送過來的訊息
}        

我把紅包都收起來,(接收訊息)            
                
                
                    
                                               
//移除observer                                           
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"postData" object:nil];
紅包都收完了,哈哈,親朋好友回家咯。。



簡單說明,哈哈,不需要理解太複雜。。。。

例說明:KVC用來傳送訊息,是很不錯的。


//kvo註冊以parserDatas為例說明:parserDatas是一個解析XML的類
[parserDatas addObserver:self forKeyPath:@"isFinished"    options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:parserDatas];




//接收變更通知
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context{
    
    if ([keyPath isEqual:@"isFinished"]) {
        BOOL isFinished=[[change objectForKey:NSKeyValueChangeNewKey] intValue];
        if (isFinished) {//如果伺服器資料接收完畢
            
            NSMutableArray *array = [[NSMutableArray alloc] init];
            [array addObjectsFromArray:parserDatas.parsedDataArray];
            //儲存資料
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            NSString *path = [DOCUMENT_PATH stringByAppendingPathComponent:@"AllXmlDataArray.bin"];
            [NSKeyedArchiver archiveRootObject:array toFile:path];
            [array release];
            //取消kvo註冊
            [object removeObserver:self
                     forKeyPath:@"isFinished"];
        }      
    }else{
        // be sure to call the super implementation
        // if the superclass implements it
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}




在parserDatas類中定義:

+ (BOOL):(NSString*)key
{
    //當這兩個值改變時,使用自動通知已註冊過的觀察者,觀察者需要實現observeValueForKeyPath:ofObject:change:context:方法
    if ([key isEqualToString:@"isFinished"])
    {
        return YES;
    }
    return [super automaticallyNotifiesObserversForKey:key];
}



傳送變更通知:

在需要跟蹤訊息記錄的函式中加入:
[self setValue:[NSNumber numberWithBool:YES] forKey:@"isFinished"];
 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"saveMessage" object:nil];

不用的時候,才登出掉的。。

一般放在dealloc....裡面。
在用之前把notification註冊掉,是為了防止多次註冊,這一般是因為這個view在程式執行時要load很多次,比如Three20的非頂層的View每次顯示的時候都重新load,這樣如果不在用之前把notification註冊掉,就會重複註冊訊息,比如每次接收到訊息就列印一句話,當你打開了n次這個view的時候,這句話就會列印n次...

- (void)awakeFromNib{

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(switchViews:)

name:@"switchViews"

  object:nil];

}

- (void)switchViews:(NSNotification*)notification{

NSNumber *viewNumber = [notification object];

NSInteger i = [viewNumber integerValue];

[self setSelectedSegmentIndex:i];

UIView *chosenView = nil;

switch (i) {

case 0:

chosenView = view1;

break;

case 1:

chosenView = view2;

break;

case 2:

chosenView = view3;

break;

default:

break;

}

if (chosenView) {

[[viewController view] bringSubviewToFront:chosenView];

}

}

- (void)dealloc{

[super dealloc];

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

@end