廣播機制傳值 iOS NSNotification
阿新 • • 發佈:2019-02-08
廣播機制分為:註冊----傳送------------接收(接收方),具體請看一下程式碼。
1,在要傳送資料的檢視頁面.m檔案處理髮送邏輯的方法裡註冊+傳送
- (IBAction)pressed:(id)sender { // [self performSegueWithIdentifier:@"second" sender:self]; NSLog(@"send message:%@",firstField.text); //頁面跳轉傳值方法二:利用notification NSDictionary *dicts = [NSDictionary dictionaryWithObjectsAndKeys:@"one1",@"one",@"two2",@"two",@"three3",@"three", nil]; //註冊(第一步) NSNotification *notification =[NSNotification notificationWithName:@"mynotification" object:firstField.text]; //傳送(第二步) [[NSNotificationCenter defaultCenter] postNotification:notification]; //註冊+傳送也可以一行完成(等效於以上兩行) [[NSNotificationCenter defaultCenter] postNotificationName:@"mynotification2" object:dicts];//傳送一個字典過去 }
notificationWithName:引數的值是自己定義,接收方以此名稱為接收標識。
2,在跳轉後,接收資料檢視頁面.m檔案中處理邏輯的方法裡 接收
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. //接受端:接受(第一步) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:@"mynotification" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler2:) name:@"mynotification2" object:nil]; } //自定義接收資訊和處理的方法(第二步) -(void) notificationHandler:(NSNotification *) notification{ secondField.text = [notification object];//收到訊息後在UItextField中顯示出來 } //自定義接收字典資訊的方法 -(void) notificationHandler2:(NSNotification *) notification2{ NSDictionary *dict = [notification2 object]; NSLog(@"receive dict :%@,forkey:%@",dict,[dict objectForKey:@"one"]); }
注意:如果註冊的notification在目標檢視沒有收到或名稱寫錯,目標檢視的相關方法就不會執行