问题
I want to use appdelegate for applicationDidBecomeActive and I want this function to use method which is placed in viewcontroller. How I am gonna do that? The only thing that I find is to access from anywhere the appdelegate.
回答1:
You need to give your applicationDelegate class a reference to the viewController that you want to call the method on. You could do this by creating an instance variable or a property of the applicationDelegate that points to your viewController that you want to be able to call the method on. If you create your viewController in the init method of your appDelegate, or in your applicationDidLoad:
method, then you can simply assign this viewController to the instance variable/property that you've created.
回答2:
You can access the root view controller of your app from within the app delegate through the window property, that is self.window.rootViewController
. The view controller that you want to access must be a child of the root view controller or at least accessible through it.
回答3:
I had the same issue of needing to call a method on my view controller from the app delegate. After some digging and reading this answer I tried to call a method (saveData was the method in question) in my view controller directly from the app delegate and it worked as required.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[self.window addSubview:rootViewController_iPad.view];
[self.window makeKeyAndVisible];
return YES;
}
-(void)applicationWillResignActive:(UIApplication *)application {
[rootViewController_iPad saveData];
}
Hope this helps.
来源:https://stackoverflow.com/questions/5290622/access-method-in-viewcontroller-from-appdelegate