What needs to be registered in applicationDidBecomeActive (AppDelegate) to access the function placed in ViewController.m?

  • self.reference.method; where reference is the reference to the controller, and method is the method to be called - Max Mikheyenko
  • In Info.plist or somewhere else you need to add some setting? - Nazar Vozniy
  • one
    You need to somehow create a reference to the desired controller in the appdelegate. but in general it is a bad practice, it would be better that the controller subscribed to the notification and did not touch the appdelegate at all - Max Mikheyenko

1 answer 1

Create a field in AppDelegate.h:

 @property UIViewController* vc; 

AppDelegate.m:

// Get the AppDelegate instance

 + (AppDelegate *)getInstance { return (AppDelegate *)[[UIApplication sharedApplication] delegate]; } 

When creating a ViewController, access the AppDelegate instance and assign the value to a variable:

ViewController.m

 #import "AppDelegate.h" -(void)viewDidLoad { [super viewDidLoad]; [AppDelegate getInstance].vc = self; } -(void)yourMethod { } 

If necessary, refer to the function from AppDelegate.m:

 -(void)applicationDidBecomeActive:(UIApplication *)application { if (self.vc) { [vc yourMethod]; } } 

I will add that this is not an ideal way, but quite working. The alternative is to subscribe for notifications and send notifications. Subscription:

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

Treatment:

 - (void)yourMethod:(NSNotification *)notification { } 

Sending:

  [[NSNotificationCenter defaultCenter] postNotificationName:@"yourMethod" object:notification.userInfo]; 

Deleting a subscription:

  - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:yourMethod object:nil]; }