通知中心也是ios進(jìn)行通信的一種機(jī)制闷愤。它可以實(shí)現(xiàn)一對多的消息通知。當(dāng)通知發(fā)出后系統(tǒng)會根據(jù)它唯一的key來添加觀察者并執(zhí)行方法遭居。
使用通知
一攘烛、發(fā)送通知
通知的唯一標(biāo)識name
NSString * const kMPRootMusicViewControllerDeleteMusicNSNotification = @"kMPRootMusicViewControllerDeleteMusicNSNotification";
一般命名方式為發(fā)出通知的類名+做了什么事情+通知;
[[NSNotificationCenter defaultCenter] postNotificationName:kMPRootMusicViewControllerDeleteMusicNSNotification object:_deletaMusicArray];
_deletaMusicArray是在發(fā)送通知時想要傳出的值;
二坟漱、添加觀察者
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(musicDidDelete:)
name:kMPRootMusicViewControllerDeleteMusicNSNotification
object:nil];
注意如果這個通知是有參數(shù)傳過來拿么函數(shù)名后面一定要跟著冒號:S蟪荨P瓤堋C倮Α!
addObserver: 觀察者
selector:收到通知執(zhí)行函數(shù)
name:這個通知的唯一標(biāo)示
三掂摔、執(zhí)行函數(shù)方法
- (void)musicDidDelete:(NSNotification *)notification
{
//獲取傳過來的參數(shù)
notification.object;
[self reloadData];
}
四、刪除通知
- (void)dealloc
{
//切記刪除通知如果不刪除會有大麻煩
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
當(dāng)你將信心放在自己身上時级历,你將永遠(yuǎn)充滿力量。