// 發送通知 -(void)btn1Click{ [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName1" object:nil]; } //註冊通知(接收,監聽,一個通知) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification1) name:@"notifyName1" object:nil]; //實現方法 -(void)notification1{ NSLog(@"接收 不帶參數的消息"); }
//發通知 -(void)btn2Click:(UIButton *)btn{ [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName2" object:[NSString stringWithFormat:@"%@",btn.titleLabel.text]]; } //註冊通知(接收,監聽,一個通知) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification2:) name:@"notifyName2" object:nil]; //實現方法 -(void)notification2:(NSNotification *)noti{ //使用object處理消息 NSString *info = [noti object]; NSLog(@"接收 object傳遞的消息:%@",info); }
//發通知 -(void)btn3Click{ NSDictionary *dic = [NSDictionary dictionaryWithObject:@"userInfo消息" forKey:@"param"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"nitifyName3" object:nil userInfo:dic]; } //註冊通知(接收,監聽,一個通知) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification3:) name:@"nitifyName3" object:nil]; //實現方法 -(void)notification3:(NSNotification *)noti{ //使用userInfo處理消息 NSDictionary *dic = [noti userInfo]; NSString *info = [dic objectForKey:@"param"]; NSLog(@"接收 userInfo傳遞的消息:%@",info); } 最後,在[接收]消息的頁面,在dealloc方法裏面移除觀察者。 -(void)dealloc{ //移除觀察者 [[NSNotificationCenter defaultCenter] removeObserver:self]; }