6

我試圖讓我的頭在NSNotificationCenter附近。如果我在我的應用程序委託是這樣的:我可以從另一個班級觀看NSNotification嗎?

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

-(void)something:(NSNotification *) notification 
{ 
    // do something 

} 

我可以以某種方式在另一個視圖控制器看這個?在我的情況下,我想在帶有表格的視圖控制器中觀看它,然後在收到通知時重新加載表格。這可能嗎?

回答

4

是的,你可以這樣做的全部目的是NSNotification,你只需要添加你想要的觀察控制器作爲觀察者完全一樣的方式,你在你的應用程序委託,它會收到通知。

你可以在這裏找到更多的信息:Notification Programming當然

+1

因此,我可以將它添加到儘可能多的視圖控制器,我希望? – cannyboy

+1

這是正確的。 – mopsled

+2

@Cannyboy是的,你可以添加儘可能多的觀察員到一個單一的通知,只要你想。 –

2

它是可能的,這是通知的整點。使用addObserver:selector:name:object:是您註冊接收通知的方式(您應該在表格視圖控制器中執行此操作),並且您可以使用postNotificationName:object:userInfo:發佈任何課程的通知。

閱讀Notofication Programming Topics瞭解更多信息。

13

是你可以做這樣的:

在A類:發佈通知

[[NSNotificationCenter defaultCenter] postNotficationName:@"DataUpdated "object:self]; 

在B類:先註冊通知,並寫來處理它的方法。 您爲該方法提供了相應的選擇器。

//view did load 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil]; 


-(void)handleUpdatedData:(NSNotification *)notification { 
    NSLog(@"recieved"); 
} 
+1

然後我在哪裏刪除觀察者? – Jatin

1

你應該只補充一點,作爲一個Observer,如果你想要那個viewController不同的行爲時通知發佈給不同的selector方法。

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


-(void)somethingOtherThing:(NSNotification *) notification 
{ 
// do something 

} 
2

您可以註冊以遵守任意數量的類中的通知。你只需要「沖洗和重複」。包括代碼登記爲(也許在viewWillAppear中:)您的視圖控制器的觀察器,然後從你的方法重新加載的tableView:

- (void)viewWillAppear:(BOOL)animated { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(something:) name:@"something" object:nil]; 
} 

-(void)something:(NSNotification *) notification 
{ 
    [self.tableView reloadData]; 
} 

這也是一個好主意,不再註銷,一旦你的視圖控制器需要通知:

- (void)viewWillDisappear:(BOOL)animated { 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 
相關問題