如何在AppDelegate的 applicationDidEnterForeground: 方法中,使用Objective-C调用UIViewController中定义的方法?

编程语言 2026-07-09

我有一个应用,其结构如下:

  • AppDelegate.h
  • AppDelegate.m
  • SceneDelegate.h
  • SceneDelegate.m
  • viewController.h
  • viewController.m

我尝试在viewController中调用一个名为viewDidEnterForeground的方法,但它没有被调用。我读到应该在AppDelegate中使用applicationDidEnterForeground。

我也尝试查找,但没有找到在AppDelegate的 applicationDidEnterForeground中,如何在viewController内调用该方法的办法。

请问有人能否告诉我怎么做,并向我解释。

我正在使用Objective-C进行编码。

解决方案

在进一步的搜索中,我找到了以下对我问题的回答。

- (void)viewDidLoad
{
    [super viewDidLoad];
//add this to viewDidLoad
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)method
{
    //action to be taken upon entering foreground
}

-(void)dealloc
//make sure to add this to remove the notification Observer from memory
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

这对我来说完全奏效。希望它也能帮助到同样遇到这个问题的其他人。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章