今天在看代碼的時候遇到了NSNotificationCenter defaultCenter這個函數,特學習了一下參數含義和用法。
建立一個繼承於UIViewControll的類,並在.m中添加如下代碼
-(void)doSomeThing:(NSNotification *)aNote{ NSDictionary *dict = [aNote object]; NSLog(@"%@",dict);}- (void)loadView{ [super loadView]; NSString *myString = @"some Value"; NSDictionary *myDict = [[NSDictionary alloc]initWithObjectsAndKeys:myString,@"first", nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil]; [[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict]; }
設定通知:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];
addObserver 這個是觀察者,就是說 在什麼地方接收通知;
selector 這個是收到通知後,調用何種方法;
name: 這個是通知的名字,也是通知的唯一標示,編譯器就通過這個找到通知的。
object: 對象,當設定為nil時,預設為所有名稱為以上訊息名稱的(notification)都接收不管寄件者是誰。
發送通知:
[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];
postNotificationName:通知的名字,也是通知的唯一標示,編譯器就通過這個找到通知的。
object:對象,當設定為nil時,預設為所有名稱為以上訊息名稱的(notification)都發送。
小例子僅僅是在一個類下的通知,實際來說通知更多的應用於不同的類之間傳遞資訊。
轉自:http://www.cnblogs.com/superhappy/archive/2012/01/31/2333177.html