为每个视图添加观察者或动态地呈现视图

问题描述:

我在本地发布通知时收到远程通知。为每个视图添加观察者或动态地呈现视图

- (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

是的,这是可能的。你想要做什么?你想达到什么目的? –

的几点思考:

  • 你也可以继承的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:高兴:)一切顺利:) –