當前位置:
首頁 >
iOS利用通知(NSNotification)进行传值
發布時間:2025/4/5
60
豆豆
生活随笔
收集整理的這篇文章主要介紹了
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。
轉載于:https://www.cnblogs.com/liuqixu/p/4757323.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的iOS利用通知(NSNotification)进行传值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: servlet第2讲(下集)----创建
- 下一篇: 小试Express