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+
You should look into singletons.
You can easily create an object that lasts through the whole application lifecycle.
Now you can call
[[YourObserverClass sharedObserver] startObserving]and you don’t have to worry about retaining it etc.