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.
(添加一条记录到接收对象的调度表,记录包含一个通知队列,队列中添加有block,可选项:通知名称,发送对象)
- (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.
(通知名称用来注册观察者;也就是说,只有包含这个名称的通知才能被添加到操作队列中去)
(如果名称为nil,通知中心将不使用通知名称来决定是否添加block到操作队列中去)
obj
The object whose notifications you want to add the block to the operation queue.
(一个对象,你将添加它的block到操作队列中)
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.
(如果对象为nil,通知中心将不使用通知发送者来决定是否添加block到操作队列中去)
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.
(当接受到通知时会执行这个block)
The block is copied by the notification center and (the copy) held until the observer registration is removed.
(通知中心将持有这个对象的副本,直到对象取消注册)
notification
The notification.
Return Value
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).
(如果一个通知出发了多个观察者的block,这些blocks也许会被同一时间并发执行(除了他们各自的队列和当前线程))
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 invoke removeObserver: or removeObserver:name:object: before any object specified by addObserverForName:object:queue:usingBlock: is deallocated.
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];
Availability
Available in iOS 4.0 and later
本文介绍iOS中NSNotificationCenter的高级使用技巧,包括如何利用addObserverForName方法注册观察者,以便在接收到特定通知时执行指定block。此外,还提供了具体的代码示例,展示如何监听本地变化通知。
3450

被折叠的 条评论
为什么被折叠?



