Can I register a class for NSNotifications? Can I use class methods with NSNotifications?

I am working on a class for my iPhone application, and I would like it to register and know the state changes of the application ( UIApplicationDidEnterBackgroundNotification , etc.). Is there a way to register a class for notifications without having to store an instance of an object in memory? I just want the corresponding notifications to call the class for init, do some things, and then leave the memory again.

Now I have the following init method:

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

and this method elsewhere in the .m class file:

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

I instantiate the class once under applicationDidLoad , but since I do nothing with it, I assume that ARC kills the object from memory and the application crashes (without any useful error codes, mind you) when I go to close this. If I switch handleEnteredBackground to a class method with a β€œ+” sign, I get invalid selection errors when closing the application.

The ultimate goal is to instantiate the class once in the life cycle of the application and its ability to respond to changes in the state of the application without any additional code outside the class. Assume iOS 5 + Xcode 4.2 +

+6
source share
2 answers

You should take a peek at singletons .

You can easily create an object that lasts through the entire application life cycle.

 + (id)sharedObserver { static dispatch_once_t once; static YourObserverClass *sharedObserver = nil; dispatch_once(&once, ^{ sharedObserver = [[self alloc] init]; }); return sharedObserver; } - (void)startObserving { // Add as observer here } 

Now you can call [[YourObserverClass sharedObserver] startObserving] and you don’t have to worry about saving it, etc.

+3
source

The following should work:

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

The selector itself:

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

You do not need to unregister the observer because the class object cannot be freed or otherwise destroyed. If you need to cancel the registration for other reasons, you can:

 [[NSNotificationCenter defaultCenter] removeObserver: [self class]]; 
+18
source

Source: https://habr.com/ru/post/908559/


All Articles