iphone消息通知--NSNotification和NSNotificationCenter

1.NSNotification:消息或通知

有三个成员变量

- (NSString *)name;

- (id)object;

- (NSDictionary *)userInfo;

通知名称:name,

消息发送者:object,代理在收到NSNotification方法里,可以回调到object

附加信息:userInfo

 

2.NSNotificationCenter:消息中心

单例模式,需要通过以下类方法访问

[NSNotificationCenter defaultCenter]

3.广播一个通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"aEvent" object:nil];

发送一个附带信息的通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"aEvent" object:nil userInfo:(NSDictionary *)aUserInfo];
aUserInfo是一个字典

直接发送一个通知

[[NSNotificationCenter defaultCenter] postNotification:(NSNotification *)notification]];

4.注册一个通知监听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onHandler:) name:@"aEvent" object:nil];

注册通知时,可以指定一个具体的广播者对象object,但不是必须的

5.移除一个监听

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"aEvent" object:nil];

6.通知要调用的方法

- (void)onHandler:(NSNotification *)notif
{
NSDictionary *user_info = [notif userInfo];
  //执行自定逻辑
}





posted @ 2012-03-26 14:06  月光的尽头  阅读(2942)  评论(0编辑  收藏  举报