iOS開發-進階:利用通知(NSNotification)進行數據傳遞

現在有兩個控制器,分別爲OneViewController、TwoViewController

點擊OneViewController中的button發出通知,並且TwoViewController接收通知打印OneViewController中傳遞過來的值


- (void)buttonClick{

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

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

    //創建通知

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

    //通過通知中心發送通知

    [[NSNotificationCenter defaultCenter] postNotification:notification];

    [self.navigationController popViewControllerAnimated:YES];

 

}

在發送通知後,在TwoViewController控制器中註冊通知監聽者,將通知發送的信息接收

- (void)viewDidLoad {

    [super viewDidLoad];

    //註冊通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(send:)name:@"sendOne" object:nil];

 

}

//將會把userInfo本身作爲參數傳進來

- (void)send:(NSNotification *)queue {

     NSLog(@"%@",queue.userInfo[@"textOne"]);

NSLog(@"%@",queue.userInfo[@"textTwo"]);

        NSLog(@"-----接收到通知------");

 

}


//銷燬時移除通知

-(void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}

發佈了26 篇原創文章 · 獲贊 5 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章