I want to listen to all notifications dispatched to the defaultCenter. Both public and private. Does anyone know how I can do this?
First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()
A notification dispatch mechanism that enables the broadcast of information to registered observers. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+
Use NSNotificationCenter's addObserverForName:object:queue:usingBlock:
OR addObserver:selector:name:object:
method and pass nil for the name and object.
The following code should do the job:
- (void)dumpNotifications { NSNotificationCenter *notifyCenter = [NSNotificationCenter defaultCenter]; [notifyCenter addObserverForName:nil object:nil queue:nil usingBlock:^(NSNotification *notification){ // Explore notification NSLog(@"Notification found with:" "\r\n name: %@" "\r\n object: %@" "\r\n userInfo: %@", [notification name], [notification object], [notification userInfo]); }]; }
Here are the docs on addObserverForName:object:queue:usingBlock:
. In particular, see the name and obj parameters.
addObserverForName:object:queue:usingBlock:
Adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender.
- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block
Parameters
name
The name of the notification for which to register the observer; that is, only notifications with this name are used to add the block to the operation queue. If you pass nil, the notification center doesn’t use a notification’s name to decide whether to add the block to the operation queue.
obj
The object whose notifications you want to add the block to the operation queue. If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to add the block to the operation queue.
queue
The operation queue to which block should be added. If you pass nil, the block is run synchronously on the posting thread.
block
The block to be executed when the notification is received. The block is copied by the notification center and (the copy) held until the observer registration is removed. The block takes one argument:
notification
The notification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With