簡體   English   中英

如何使用NSNotification從另一個類調用函數

[英]how to call function from another class with NSNotification

我有A班和B班。

在B類中,我創建了如下函數:

-(void)conferance:(NSNotification *)notification {

    [self conferanceConfirming:provisioningURL];

}

在AI類中,嘗試以這種方式調用B類中的函數:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conferance:)name:nil object:nil];

但這是行不通的。 任何幫助贊賞。

在B類中,您需要寫

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conferance:)name:@"ConferanceNotification" object:nil];

從A類開始,您只需致電

[[NSNotificationCenter defaultCenter] 
        postNotificationName:@"ConferanceNotification" 
        object:nil];

“ ConferanceNotification”是通知名稱,由類b觀察。 然后它將調用您定義的注冊選擇器。

您需要在B類中添加addObserver並在此處編寫方法。

這是用於B類的代碼:

-(void)conferance:(NSNotification *)notification {

    [self conferanceConfirming:provisioningURL];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conferance:)name:nil object:nil];
}

從類A調用方法:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ConferanceNotification" 
        object:nil];

這是NSNotification的簡要文檔

您在AddObserver中犯了錯誤。 如果未添加NSNotificationObserver,則無法調用它。 因此,您需要先添加觀察者,然后再調用它。

暫無
暫無

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

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