1

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?

eric.mitchell
  • 8,817
  • 12
  • 54
  • 92

1 Answers1

4

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].

XJones
  • 21,959
  • 10
  • 67
  • 82
  • How will that solve my problem? Change the addObserver calls? Could you elaborate? – eric.mitchell Nov 23 '11 at 00:20
  • Perfect explanation. And @Rickay `viewDidLoad` is the perfect place for your code. Just remember to `removeObserver:` in `viewDidUnload`. – NJones Nov 23 '11 at 02:35
  • One clarfication on @NJones comment. Where you add/remove the observer depends on what you do based on the notification. If it is possible for the view controller to be alive while it's view is unloaded (e.g. when in a `UITabBarController` or a `UINavigationController` stack, etc) and you want to handle the notification even if the view is unloaded then you should add the observer in your `init...` method instead of `viewDidLoad`. Either way, you should also stop observing in `dealloc` b/c the controller could be dealloc'ed w/o `viewDidUnload` being called. – XJones Nov 23 '11 at 05:41
  • @XJones, Nice clarification, and in this case it could very well apply. Thanks. – NJones Nov 23 '11 at 05:50