从app delegate调用实例函数

max*_*hud 1 ios sprite-kit

我有一个名为game.h的类,它有一个名为pause的实例方法.当我的游戏进入后台时,如何从应用代理中调用此功能?

我知道你使用- (void)applicationWillResignActive:(UIApplication *)application,但我想在我现有的实例上调用暂停.

nhg*_*rif 6

NSNotificationCenter.

在您的game类实例中,添加selfUIApplicationWillResignActiveNotification通知的观察者.


在您的game课程中,您需要以下代码段:

[[NSNotificationCenter defaultCenter] 
    addObserver:self
    selector:@selector(pause) 
    name:UIApplicationWillResignActiveNotification
    object:nil];
Run Code Online (Sandbox Code Playgroud)

这可能应该进入init.

此通知被触发applicationWillResignActive.该addObserver:selector:name:object:方法将您的对象设置为在收到该通知时调用您告诉它的选择器.


不要忘记以self观察员身份移除dealloc.

game.m's @implementation:

- (void)dealloc {
    // If not using ARC, then be sure to [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
Run Code Online (Sandbox Code Playgroud)