通知:
kvo ______ key? value observer
觀察者機(jī)制
使用通知時(shí)需要注意:要先監(jiān)聽(tīng)通知再發(fā)送通知
//注冊(cè)監(jiān)聽(tīng)通知
//位置:一般寫(xiě)在想要監(jiān)聽(tīng)一個(gè)通知的類(lèi)中的視圖將出現(xiàn)的方法中或者didLoad方法中
[[NSNotificationCenter ? defaultCenter]addObserver:self ? selector:@selector(觸發(fā)方法名字) ? name:@“通知的名字”object:參數(shù)(可以為nil)];
//發(fā)送通知
//通知的名字要一致
[[NSNotificationCenter ? defaultCenter] postNotificationName:@“通知的名字”object:參數(shù)];
- (void)dealloc {
//注冊(cè)和注銷(xiāo)成對(duì)出現(xiàn)
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"通知的名字" object:nil];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
//通知:NSNotification
//通知中心: NSNotificationCenter觀察發(fā)送都在通知中心中操作(單例類(lèi))不管在哪里去獲取得到的都是同一個(gè)對(duì)象通知中心這個(gè)單例獲得方法[NSNotificationCenter defaultCenter];
//通知中心
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//通知---initWithName:通知名字 object:發(fā)送者(nil self傳參數(shù))? userInfo:字典類(lèi)型附加說(shuō)明信息
NSNotification * notify = [[NSNotification alloc] initWithName:@"000" object:@"99999" userInfo:@{@"color":@"red"}];
//1.發(fā)送通知: post
[center postNotification:notify];
//MRC下需要release
[notify release];
//2.post? object:發(fā)送通知的對(duì)象(nil self傳參)
[center postNotificationName:@"001" object:nil];
//3.post? userInfo:字典類(lèi)型附加說(shuō)明信息
[center postNotificationName:@"002" object:selfuserInfo:nil];
/*監(jiān)聽(tīng)觀察通知在接收消息的類(lèi)中寫(xiě)A(post) ------> B(observe)
*addObserver:添加觀察著
*selector:收到通知執(zhí)行的方法:傳對(duì)象
*name:要觀察的通知的名字
*object :對(duì)發(fā)送通知者的要求如果設(shè)置為騰訊那么只會(huì)關(guān)心騰訊的通知一般nil
*/
//[NSNotificationCenter defaultCenter]addObserver:<#(nonnull id)#> selector:<#(nonnull SEL)#> name:<#(nullable NSString *)#> object:<#(nullable id)#>];
[center addObserver:self selector:@selector(receive:) name:@"要觀察的通知的名字" object:nil];
//發(fā)通知之前一定要先確定觀察者發(fā)送的通知和要觀察的通知的名字要一致
//[NSNotificationCenter defaultCenter]addObserver:<#(nonnull id)#> selector:<#(nonnull SEL)#> name:<#(nullable NSString *)#> object:<#(nullable id)#>];
//[NSNotificationCenter defaultCenter]postNotificationName:<#(nonnull NSString *)#> object:<#(nullable id)#>];
//發(fā)送的通知不要重名汉规,注冊(cè)通知之前最好要先移除這個(gè)通知,防止這個(gè)通知已經(jīng)被注冊(cè)
//最優(yōu)寫(xiě)法:先移除后添加
//[NSNotificationCenter defaultCenter]removeObserver:<#(nonnull id)#> name:<#(nullable NSString *)#> object:<#(nullable id)#>];
}
-(void)receive:(NSNotification*)notify{
}