NSNotification 通知

通知:

kvo ______ key? value observer

觀察者機制

使用通知時需要注意:要先監(jiān)聽通知再發(fā)送通知

//注冊監(jiān)聽通知
//位置:一般寫在想要監(jiān)聽一個通知的類中的視圖將出現(xiàn)的方法中或者didLoad方法中

[[NSNotificationCenter ? defaultCenter]addObserver:self ? selector:@selector(觸發(fā)方法名字) ? name:@“通知的名字”object:參數(shù)(可以為nil)];

//發(fā)送通知
//通知的名字要一致

[[NSNotificationCenter ? defaultCenter] postNotificationName:@“通知的名字”object:參數(shù)];

- (void)dealloc {

//注冊和注銷成對出現(xiàn)

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"通知的名字" object:nil];

[super dealloc];

}

- (void)viewDidLoad {

[super viewDidLoad];

//通知:NSNotification

//通知中心: NSNotificationCenter觀察發(fā)送都在通知中心中操作(單例類)不管在哪里去獲取得到的都是同一個對象通知中心這個單例獲得方法[NSNotificationCenter defaultCenter];

//通知中心

NSNotificationCenter * center = [NSNotificationCenter defaultCenter];

//通知---initWithName:通知名字 object:發(fā)送者(nil self傳參數(shù))? userInfo:字典類型附加說明信息

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ā)送通知的對象(nil self傳參)

[center postNotificationName:@"001" object:nil];

//3.post? userInfo:字典類型附加說明信息

[center postNotificationName:@"002" object:selfuserInfo:nil];

/*監(jiān)聽觀察通知在接收消息的類中寫A(post) ------> B(observe)
*addObserver:添加觀察著
*selector:收到通知執(zhí)行的方法:傳對象
*name:要觀察的通知的名字
*object :對發(fā)送通知者的要求如果設置為騰訊那么只會關心騰訊的通知一般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ā)送的通知不要重名,注冊通知之前最好要先移除這個通知,防止這個通知已經(jīng)被注冊

//最優(yōu)寫法:先移除后添加

//[NSNotificationCenter defaultCenter]removeObserver:<#(nonnull id)#> name:<#(nullable NSString *)#> object:<#(nullable id)#>];

}

-(void)receive:(NSNotification*)notify{

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容