2013年8月27日 星期二

用 NSNotification 註冊事件發生通知簡單3部曲



1. Add- 監聽事件的發生,一發生的話就執行Selector..

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                          selector:@selector(didDismissSecondViewController) 
                                          name:@"ViewControllerDismissed"  
                                         object:nil];

2. Post- 事件發生時! 發出通知讓其他有加入此通知的地方去執行相對應的動作!

    [[NSNotificationCenter defaultCenter] postNotificationName:@"SecondViewControllerDismissed" 
                                          object:nil  
                                          userInfo:nil];

3. Remove- 移除掉Observer,避免收到不必要的通知

    暴力法: 寧可錯殺一百也不願放過一個 草菅人命
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    明察秋毫法: 用name去找.. 關掉這部分的通知
    [[NSNotificationCenter defaultCenter] 
removeObserver:self name:@"SecondViewControllerDismissed" object:nil]; 


簡化精華三部曲,

可以用來傳遞參數或控制UI變化等等,上手後超級實用喔!



沒有留言:

張貼留言