注册观察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(execute:) name:@"NotificationName" object:nil];
观察者 self 在收到名为 @"NOTIFICATION_NAME" 的事件是执行 @selector(execute:),最后一个参数是表示会对哪个发送者对象发出的事件作出响应,nil 时表示接受所有发送者的事件。
还有一种注册观察者的方式是用方法:
- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block
通知相应的观察者:
NSString *strObj = [[NSString alloc] initWithString@"tset"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object: strObj];
-(void)execute:(id)sender
{
NSNotification *notFic = (NSNotification*)sender; NSString *strName = [notFic name];// 通知的名字@"NotificationName"
NSString *strRes = [notFic object];//传过来的参数
}
第三个参数是要发送的数据
删除观察者:
[[NSNotificationCenter defaultCenter] removeObserver:self];