开发者

How to create a reference to on of my view controllers from my app delegate?

开发者 https://www.devze.com 2023-02-05 09:18 出处:网络
Hi I was wondering, how can I create a reference to one o开发者_开发知识库f my view controllers from my app delegate? I\'d like to call a specific method (of my view controller) from the delegate when

Hi I was wondering, how can I create a reference to one o开发者_开发知识库f my view controllers from my app delegate? I'd like to call a specific method (of my view controller) from the delegate when my app enters foreground.


  1. Make an member ivar pointer of the same class in your *AppDelegate, set it to nil when launching, set its property to "assign".
  2. When the specific view controller is created and loaded in the memory, in this controller's viewDidLoad method:

    [[[UIApplication sharedApplication] delegate] setThatSpecialContrller:self];

  3. When this controller has to be deallocated at some point, you use a similar line of code to again set the pointer to nil.

  4. Do a check every time your app is coming from the background to the foreground, if the pointer is not nil, use this not-nil reference to call your specific controller and its method.


Alternatively, you can listen for the UIApplicationWillEnterForegroundNotification notification.

- (void)viewDidLoad {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(applicationWillEnterForeground:) UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)viewDidUnload {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


Alternative approach, that diwup mentioned, is nicely and shortly described in section "Hooking Up The Left With the Right" in this tutorial.

0

精彩评论

暂无评论...
验证码 换一张
取 消