【问题标题】:Using instance methods in the app delegate在应用委托中使用实例方法
【发布时间】:2014-07-21 23:13:27
【问题描述】:

当我的应用程序进入后台模式并退出时,我想在我的应用程序委托中运行一个名为“pauseGame”的 BPGameController 类的实例方法,并在应用程序再次激活时运行一个名为“resumeGame”的实例方法,我'我尝试了一些不同的方法,但到目前为止没有一个对我有用

【问题讨论】:

  • 获取对现有BPGameController 实例的引用并调用该方法。
  • 您为什么要从应用程序委托中执行此操作?设置您的控制器以响应相关的通知。

标签: ios methods instance appdelegate


【解决方案1】:

在 BPGameController 的 viewDidLoad 方法中注册通知如下:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseGame)
                                             name:UIApplicationDidEnterBackgroundNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeGame)
                                             name:UIApplicationDidBecomeActiveNotification object:nil];

当你完成后,将自己从观察中移开。

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];

【讨论】:

  • 您忽略了这个答案中真正重要的部分。您必须在 dealloc 方法中删除观察者,否则应用程序可能会在某个时候崩溃。
  • 我已添加它以获得更完整的答案。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多