簡體   English   中英

如何在目標c中使用NSNotification

[英]how to use NSNotification in objective c

我不知道如何在我們的iPhone應用程序中使用NSNotification。 還有一個關於委托和NSNotification之間區別的懷疑,因為兩者都通過對象進行通信。

並給出實際的例子。

=> NSNotificationCenter提供了一個集中式中心,應用程序的任何部分都可以通過該中心通知應用程序的任何其他部分並向其通知更改。

=>觀察者在通知中心注冊,以指定的動作響應特定事件。

=>每次事件發生時,通知都會通過其分發表,並向該事件的所有注冊觀察者發送消息。

在目標C中使用NS通知

//從要傳遞數據的地方寫

[[NSNotificationCenter defaultCenter]postNotificationName:@"TeamTable" object:hdImage userInfo:nil];

這里

** TeamTable是通知觀察者名稱(唯一名稱)

** hdImage是您要傳遞給另一個控制器的數據

現在,在要從中接收數據的Controller中編寫這些代碼

-(void)viewWillAppear:(BOOL)animated{

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(detailsData:) name:@"TeamTable" object:nil];
}

-(void)detailsData:(NSNotification*)sender{
//In sender it contain All received data
}

重要的是,對象必須在取消分配觀察者之前除去觀察者,以防止進一步發送消息。

-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"TeamTable" object:nil];

}

有關NS通知的更多詳細信息,請訪問此鏈接http://nshipster.com/nsnotification-and-nsnotificationcenter/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM