ios 从应用程序委托调用 UIViewController 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18950670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling UIViewController method from app delegate
提问by Sarp Kaya
I know there are duplicates of this question but my situation is different here.
我知道这个问题有重复,但我的情况在这里不同。
When user goes back to the home (void)applicationDidEnterBackgroundgets invoked from the AppDelegateclass. However once user presses home button, I don't want user to see this view controller again, so I have a method named (void)goToBeginningthat switches to another view controller. I want to be able to call this method from AppDelegate. I don't really want to use NotificationCenterfor this. Also the picked solution here:
Calling view controller method from app delegatedoes not work for me as it initialises new object whereas I want to be able to call an object that is already in the view. How can I do that? I am using iOS 7 and XCode 5.
当用户回到家(void)applicationDidEnterBackground时,AppDelegate该类会被调用。然而,一旦用户按下主页按钮,我不希望用户再次看到这个视图控制器,所以我有一个名为(void)goToBeginning切换到另一个视图控制器的方法。我希望能够从 AppDelegate 调用此方法。我真的不想用NotificationCenter这个。还有这里选择的解决方案:
从应用程序委托调用视图控制器方法对我不起作用,因为它初始化了新对象,而我希望能够调用已经在视图中的对象。我怎样才能做到这一点?我正在使用 iOS 7 和 XCode 5。
回答by sunkehappy
- Notification. But you don't want this.
- You can get the reference to your that
viewControllerin theAppDelegate. Than call that(void)goToBeginningmethod in the(void)applicationDidEnterBackground
- 通知。但你不想要这个。
- 您可以
viewController在AppDelegate. 比(void)goToBeginning在(void)applicationDidEnterBackground
For example: In your ViewController
例如:在您的 ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.myViewController = self;
}
And in your AppDelegate:
而在你的AppDelegate:
@class MyViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (weak, nonatomic) MyViewController *myViewController;
@end
And in the AppDelegate's implementation:
在AppDelegate的实现中:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self.myViewController goToBeginning];
}

