iOS通知傳值的使用

?關(guān)于其他使用,點擊>>>>?iOS NSNotificationCenter 使用姿勢詳解

通知 是在跳轉(zhuǎn)控制器之間常用的傳值代理方式,除了代理模式,通知更方便、便捷,一個簡單的Demo實現(xiàn)通知的跳轉(zhuǎn)傳值.

iOS通知傳值的使用

輸入所要發(fā)送的信息 ,同時將label的值通過button方法調(diào)用傳遞,

- (IBAction)buttonClick:(id)sender {

//添加 字典,將label的值通過key值設(shè)置傳遞

NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.textFieldOne.text,@"textOne",self.textFieldTwo.text,@"textTwo", nil];

//創(chuàng)建通知

NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];

//通過通知中心發(fā)送通知

[[NSNotificationCenter defaultCenter] postNotification:notification];

[self.navigationController popViewControllerAnimated:YES];

}

在發(fā)送通知后,在所要接收的控制器中注冊通知監(jiān)聽者,將通知發(fā)送的信息接收

- (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:是刪除通知中心保存的調(diào)度表一個觀察者的所有入口,而removeObserver:name:object:是刪除匹配了通知中心保存的調(diào)度表中觀察者的一個入口。

這個比較簡單,直接調(diào)用該方法就行。例如:

[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];

注意參數(shù)notificationObserver為要刪除的觀察者,一定不能置為nil。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容