通知的機制是一對多,而block和delegate的機制是一對一,通知是好用,但小伙伴麼要記得通知比較耗性能哦~~~
誰要發送消息,誰就發出通知,誰要接受消息,誰就銷毀通知.
下面直接來看代碼:
//發出通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:image]; //誰接受通知 誰就銷毀通知 - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(valueChanged:) name:@"notification" object:nil]; } - (void)valueChanged:(NSNotification *)notification{ // object 就是傳過來的參數 self.imgView.image = notification.object; } //在對象銷毀的時候移除通知 -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }