Alex Rivera | Logout

Can I Register a Class for NSNotifications? Can I use Class Methods with NSNotifications?

Asked 2012-02-15T21:41:48.697
8

I'm working on a class for my iPhone app, and I'd like it to register for and be aware of application state changes (UIApplicationDidEnterBackgroundNotification, etc). Is there a way to register a class for notifications without having to keep an instantiated object in memory? I just want to have the appropriate notifications call the class to init, do some stuff, and then leave memory again.

Right now I have the following in the init method:

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

and this method elsewhere in the .m file of the class:

- (void) handleEnteredBackground {
    NSLog(@"Entered Background"); }

I instantiate the class once under applicationDidLoad, but since I don't do anything with it I presume ARC kills the object from memory and the app crashes (without any useful error codes, mind you) when I go to close it. If I switch handleEnteredBackground to a class method with a "+" sign, I get invalid selector errors when I close the app.

The end goal is to instantiate a class once in the lifecycle of an app and have it be able to respond to app state changes without any additional code outside the class. Assume iOS 5 + Xcode 4.2+

Edit
Report

1 Answer

20

The following should work:

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

The selector itself:

+ (void) handleEnteredBackground: (NSNotification *) notification
{
}

You don't have to unregister the observer, because the class object cannot be deallocated or otherwise destroyed. If you need to unregister the observer for other reasons, you can:

[[NSNotificationCenter defaultCenter] removeObserver: [self class]];
answered 2012-02-16T06:09:18.020

Your Answer