Question

I am posting a notification locally in the app when ever I receive a remote notification.

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

I have added an observer to the view in the function viewWillAppear() and remove the observer in viewWillDisappear().

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

and
[[NSNotificationCenter defaultCenter] removeObserver:self];

My question is I want to override every viewWillAppear and viewWillDisappear functions in all *.m files that use these functions in my app.

or how can I dynamically add an observer (like above) to the present view and remove the observer when that view disappears. it should be like a global action whenever view changes observer to be added and removed when it changes again.

Is this possible? if so please guide me.

thanks in advance.

Was it helpful?

Solution

Some thoughts:

  • You can subclass UIViewController and implement these method in the subclass-ed view controller class. Then you need to create all your views as the subclass of this UIViewController.

Example:

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

And create all your view controller as the subclass of CustomViewController.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top