2013-07-23 28 views
0

我在本地發佈通知時收到遠程通知。爲每個視圖添加觀察者或動態地呈現視圖

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
    NSLog(@"Received notification: %@", userInfo); 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NEWMESSAGE" object:nil userInfo:userInfo]; } 

我添加觀察者在函數viewWillAppear中(視圖)和除去觀察者在viewWillDisappear()。

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

and 
[[NSNotificationCenter defaultCenter] removeObserver:self]; 

我的問題是要覆蓋在我的應用程序使用這些功能,所有的* .m文件每viewWillAppear中和viewWillDisappear功能。

或者我該如何動態地將觀察者(如上所述)添加到當前視圖中,並在視圖消失時移除觀察者。它應該像全局行爲一樣,只要視圖改變觀察者,當它再次改變時被添加和移除。

這可能嗎?如果是的話請指導我。

在此先感謝。

+0

正如你所說的你想重寫viewwillappear和viewwilldisappear函數在每個控制器中,做到這一點,並添加和刪除觀察者在那..問題是什麼。 – Suryakant

+0

是的,這是可能的。你想要做什麼?你想達到什麼目的? –

回答

2

的幾點思考:

  • 你也可以繼承的UIViewController並實現在子類中,編輯視圖控制器類這些方法。然後,您需要創建所有視圖作爲此UIViewController的子類。

例子:

//Creating a custom subclass of UIViewController 
@interface CustomViewController : UIViewController 
@end 

@implementation CustomViewController 

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

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

@end 

,並創造一切的視圖控制器作爲CustomViewController的子類。

+0

非常感謝 –

+0

@VardhanDG:高興:)一切順利:) –