1. 程式人生 > >iOS_介面傳值——通知傳值

iOS_介面傳值——通知傳值

註冊一個通知來實現介面間的傳值,這種方法一般用在介面返回時比較多一點。

1、基本邏輯:


點選button進入下一個介面,在UITextField中輸入任意字串後,點選右上角的傳值,返回主頁,主頁上顯示

UITextField所輸入的值。

2、程式碼實現:

(1)在第二個控制器.m檔案中:

- (IBAction)sendInfo:(id)sender {
    NSDictionary *dataDic = [NSDictionary dictionaryWithObject:self.info.text forKey:@"info"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"infoNotification" object:nil userInfo:dataDic];
    [self.navigationController popViewControllerAnimated:YES];
}
這個是傳值item的點選事件,將所傳的資訊用字典傳出去。

(2)在主頁的控制器.m中:

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"infoNotification" object:nil];
}

-(void)receiveNotification:(NSNotification *)infoNotification {
    NSDictionary *dic = [infoNotification userInfo];
    NSString *str = [dic objectForKey:@"info"];
    self.infoLabel.text = str;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

接收通知、登出通知的程式碼。

如果有什麼看不懂的可以看我這一篇註釋的部落格:

這裡面講的比較清楚,使用通知的時候要注意了,前後使用的名稱一定要一致,最好自己複製下,防止寫錯了。

這是第二篇關於介面傳值方法的介紹,之前的一篇請參考連結: