NSNotificationCenter addObserver 没有响应
在我的应用程序(游戏)中,当按下中心/主页或锁定按钮时,我尝试使用 NSNotificationCenter 暂停和恢复游戏。这是我正在使用的代码:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(pauseLayer:)
name:UIApplicationWillResignActiveNotification
object:self.view.layer.sublayers];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(pauseLayer:)
name:UIApplicationDidEnterBackgroundNotification
object:self.view.layer.sublayers];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(resumeLayer:)
name:UIApplicationWillEnterForegroundNotification
object:self.view.layer.sublayers];
我已经尝试将其放在很多不同的地方,例如 viewDidLoad、viewDidAppear、initWithNibNameOrNil,但是尽管它们都被调用,但方法pauseLayer和resumeLayer永远不会被调用,即使应用程序委托方法也是如此做。为什么这段代码不起作用?
In my app (game) I'm trying to use the NSNotificationCenter to pause and resume the game when either the center/home or lock button is pressed. This is the code I'm using:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(pauseLayer:)
name:UIApplicationWillResignActiveNotification
object:self.view.layer.sublayers];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(pauseLayer:)
name:UIApplicationDidEnterBackgroundNotification
object:self.view.layer.sublayers];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(resumeLayer:)
name:UIApplicationWillEnterForegroundNotification
object:self.view.layer.sublayers];
I have experimented with putting it in lots of different places like viewDidLoad, viewDidAppear, initWithNibNameOrNil, but although they are all being called, the methods pauseLayer and resumeLayer never get called, even though the app delegate method does. Why doesn't this code work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更改
addObserver
调用并从object
参数中删除self.view.layer.sublayers
。将其更改为nil
。编辑:更多信息
当然。
object
参数告诉NSNotificationCenter
您想要观察哪个对象的通知。当您指定 self.view.layer.sublayers 时,您将观察到仅由 sublayers 数组发送的 UIApplicationWillEnterForegroundNotification 等。当然,sublayers
数组不会发送此通知。当您指定object:nil
时,您正在观察来自任何对象的通知。在这种情况下这是合适的。如果您想指定一个对象,则为[UIApplication sharedApplication]
。change the
addObserver
calls and removeself.view.layer.sublayers
from theobject
param. change it tonil
.EDIT: more info
Sure. The
object
param tellsNSNotificationCenter
which object's notification you want to observe. When you specifyself.view.layer.sublayers
you are observingUIApplicationWillEnterForegroundNotification
et al only sent by thesublayers
array. Of course, thesublayers
array does not send this notification. When you specifyobject:nil
you are observing the notification from any object. That is appropriate in this case. If you want to specify an object it would be[UIApplication sharedApplication]
.