I want to listen to all notifications dispatched to the defaultCenter. Both public and private. Does anyone know how I can do this?
问题:
回答1:
Use NSNotificationCenter's addObserverForName:object:queue:usingBlock:
OR addObserver:selector:name:object:
method and pass nil for the name and object.
Example
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]);
}];
}
Docs
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.