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變化等等,上手後超級實用喔!



Singleton - 只要instance一次就可以當全域變數的方法


一般instance的方式:
myclass *instance = [[myclass alloc] init];

Singleton物件的方式:

myclass *instance = [myclass sharedInstance];


對於同一個物件,要在不同的view上面做共享時候

Singleton 是一個非常好用的方式

有點像是全域( global variable )變數一樣

在任何地方都可以共享他的value,

也透過這個方法作參數的傳遞.