【问题标题】:application enter in background IOS?应用程序进入后台IOS?
【发布时间】:2014-10-21 15:07:03
【问题描述】:

有一种方法可以在调用应用程序委托的方法“applicationDidEnterBackground”但只是获取应用程序对象时通知对象。

当应用程序进入后台时我需要执行一些操作,但我只能通过“[UIApplication sharedApplication]”访问应用程序对象。

注意:我需要这 3 个方法 applicationWillTerminate、applicationWillEnterForeground、applicationDidEnterBackground 但我无法访问 applicationDelegate 方法。

【问题讨论】:

  • 这些方法都应该在AppDelegate.m中。你的问题能具体一点吗?
  • Morgan 是对的,所有这些方法都在 AppDelegate.m 中可用。
  • 摩根是对的,但我无法使用这些方法。

标签: ios objective-c


【解决方案1】:

您可以使用NSNotificationCenter 通知您的班级这些方法正在被调用。 在 init 中注册正确的通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminateNotification:) name:UIApplicationWillTerminateNotification object:nil];

这将调用这个方法,你必须将它添加到你的类中:

- (void)applicationWillTerminateNotification::(NSNotification *)notifictaion{
}

您要添加的通知是:UIApplicationWillTerminateNotificationUIApplicationWillEnterForegroundNotificationUIApplicationDidEnterBackgroundNotification

不要忘记在你的班级的dealloc 中取消注册你的班级实例,即使在 ARC 中也是如此:

-(void) dealloc {
   [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];

}

【讨论】:

    【解决方案2】:

    我遇到了类似的问题。我的解决方案是获取 AppDelegate 的实例并将我的对象注册为观察者:

    AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate addApplicationDidEnterBackgroundObserver:myobject];
    // and later...
    [appDelegate removeObserver:myobject];
    

    确保 rckoenes 的解决方案更优雅。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多