所謂通知中心傳值,指的是借助 NSNotification 在多個頁面之間傳遞數據。它的長處是可以跨越任意層級——最典型的用法就是把後面頁面的值回傳給前面的頁面。
假設導航層級是 第一界面 → 第二界面 → 第三界面,現在要讓第三界面的數據回到第一界面。步驟如下:
dealloc 中把監聽移除掉;object 上即可。// 通知中心是個單例
NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
// 注册監聽:第三個參數是通知名稱,系統靠它來區分不同事件
[notiCenter addObserver:self
selector:@selector(receiveNotification:)
name:@"cesuo"
object:nil];
// 收到通知後的回調
- (void)receiveNotification:(NSNotification *)noti {
// NSNotification 有三個屬性:
// name —— 通知的名稱
// object —— 這裡裝著第三個界面傳過來的數據
// userInfo —— 附帶的信息,通常是字典
NSLog(@"%@ === %@ === %@", noti.object, noti.userInfo, noti.name);
}
// 在 dealloc 中移除監聽,避免野指針
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 同樣是拿單例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 發送通知
// name —— 填第一界面注册時用的名字,系統靠它找到響應方
// object —— 要傳遞的值
// userInfo —— 一個字典,如需一次傳多個參數,提前把數據裝進字典即可
[center postNotificationName:@"cesuo"
object:@"zhangheng"
userInfo:dic];
userInfo 字典,比塞在 object 裡更清晰;dealloc,否則容易出現重複回調或崩潰。