iOS利用通知(NSNotification)進行傳值

來源:互聯網
上載者:User

iOS利用通知(NSNotification)進行傳值

 

通知 是在跳轉控制器之間常用的傳值代理方式,除了代理模式,通知更方便、便捷,一個簡單的Demo實現通知的跳轉傳值.
iOS通知傳值的使用
輸入所要發送的資訊 ,同時將label的值通過button方法調用傳遞,
- (IBAction)buttonClick:(id)sender {
//添加 字典,將label的值通過key值設定傳遞
NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.textFieldOne.text,@textOne,self.textFieldTwo.text,@textTwo, nil];
//建立通知
NSNotification *notification =[NSNotification notificationWithName:@tongzhi object:nil userInfo:dict];
//通過通知中樞發送通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
[self.navigationController popViewControllerAnimated:YES];

}
在發送通知後,在所要接收的控制器中註冊通知監聽者,將通知發送的資訊接收
- (void)viewDidLoad {
[super viewDidLoad];
//註冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@tongzhi object:nil];

}
- (void)tongzhi:(NSNotification *)text{
NSLog(@%@,text.userInfo[@textOne]);
NSLog(@-----接收到通知------);

}
移除通知:removeObserver:和removeObserver:name:object:
其中,removeObserver:是刪除通知中樞儲存的調度表一個觀察者的所有入口,而removeObserver:name:object:是刪除匹配了通知中樞儲存的調度表中觀察者的一個入口。
這個比較簡單,直接調用該方法就行。例如:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
注意參數notificationObserver為要刪除的觀察者,一定不能置為nil。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.