How to create a reference to on of my view controllers from my app delegate?
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.
- Make an member ivar pointer of the same class in your *AppDelegate, set it to nil when launching, set its property to "assign".
When the specific view controller is created and loaded in the memory, in this controller's viewDidLoad method:
[[[UIApplication sharedApplication] delegate] setThatSpecialContrller:self];
When this controller has to be deallocated at some point, you use a similar line of code to again set the pointer to nil.
- 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.
精彩评论