addObserver:selector:name:object:
Adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria: notification name and sender.
Parameters
-
notificationObserver
-
Object registering as an observer. This value must not be
nil
.指定观察者是谁,此参数不能为空,一般为self
notificationSelector
-
Selector that specifies the message the receiver sends notificationObserver to notify it of the notification posting. The method specified by notificationSelector must have one and only one argument (an instance of
NSNotification
).观察者要响应的方法,此方法必须要有而且只有一个参数'NSNotification'
notificationName
-
The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.
If you pass
nil
, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.通知的名称,在通知中心注册的名字
notificationSender
-
The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.
If you pass
nil
, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.谁发送的这个通知
postNotificationName:object:userInfo:
Creates a notification with a given name, sender, and information and posts it to the receiver.
- (void)postNotificationName:( NSString *) notificationName object:(id) notificationSender userInfo:( NSDictionary*) userInfoParameters
-
notificationName
-
The name of the notification.
notificationSender
-
The object posting the notification.
userInfo
-
Information about the the notification. May be
nil
.
-
//点击按钮
- (IBAction)btnPressed:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"hello" object:nil userInfo:[NSDictionary dictionaryWithObject:@"YES" forKey:@"result"]];
}
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hello:) name:@"hello" object:nil];
- (void)hello:(NSNotification *)sender
{
NSDictionary *dict = [sender userInfo];
NSString *str = [dict objectForKey:@"result"];
NSLog(@"str = %@",str);
}
//NSNotification的使用
@interface NSNotification : NSObject <NSCopying, NSCoding>
- (NSString *)name;
- (id)object;
- (NSDictionary *)userInfo;
@end