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?
change the addObserver
calls and remove self.view.layer.sublayers
from the object
param. change it to nil
.
EDIT: more info
Sure. The object
param tells NSNotificationCenter
which object's notification you want to observe. When you specify self.view.layer.sublayers
you are observing UIApplicationWillEnterForegroundNotification
et al only sent by the sublayers
array. Of course, the sublayers
array does not send this notification. When you specify object: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]
.