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 *)queueusingBlock:(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.[NSNotificationCenter addObserverForName] - 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.
Return Value of [NSNotificationCenter addObserverForName]
An opaque object to act as the observer.
Discussion
If a given notification triggers more than one observer block, the blocks may all be executed concurrently with respect to one another (but on their given queue or on the current thread).
Example of [NSNotificationCenter addObserverForName]
The following example shows how you can register to receive locale change notifications.
NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; |
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; |
self.localeChangeObserver = [center addObserverForName :NSCurrentLocaleDidChangeNotification object:nil |
queue:mainQueue usingBlock:^(NSNotification *note) { |
NSLog(@"The user's locale changed to: %@", [[NSLocale currentLocale] localeIdentifier]); |
}]; |
To unregister observations, you pass the object returned by this method to
removeObserver:
. You must invokeremoveObserver:
or removeObserver:name:object:
before any object specified by addObserverForName :object:queue:usingBlock:
is deallocated.NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; |
[center removeObserver:self.localeChangeObserver]; |