NSNotificationCenter 的使用

NSNotificationCenter 的使用

1,定义一个方法

-(IBACtion)shuchu{ }

2,对象注册,并附带信息[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shuchu) name:@"Method" object:nil]

3,发送通知信息

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

4. 不用的时候,才注销掉的。。

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


什么是Notification?

这个要求其实也很容易实现. 每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我). 我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗). center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做poster

很多的标准Cocoa类会发送notifications: 在改变size的时候,Window会发送notification; 选择table view中的一行时,table view会发送notification;我们可以在在线帮助文档中查看到标准cocoa对象发送的notification

在对象释放前,我们必须从notification center移除我们注册的observer. 一般我们在dealloc方法中做这件事


附:注册键盘升启关闭消息

  1. //键盘升起
  2. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  3. //键盘降下
  4. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];



NSNotification类

提供给observer的信息包裹. notification对象有两个重要的成员变量: name 和 object.

- (NSString *)name;

- (id)object;

- (NSDictionary *)userInfo;我们想要notification对象传递更多的信息


+ (id)notificationWithName:(NSString *)aName object:(id)anObject;

+ (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary*)aUserInfo;




NSNotificationCenter类

+ (id)defaultCenter;返回notification center [类方法,返回全局对象, 单件模式.cocoa的很多的全局对象都是通过类似方法实现]

 

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

如果notificationName为nil. 那么notification center将anObject发送的所有notification转发给observer

. 如果anObject为nil.那么notification center将所有名字为notificationName的notification转发给observer


- (void)postNotification:(NSNotification *)notification;

- (void)postNotificationName:(NSString *)aName object:(id)anObject;

- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary*)aUserInfo;


- (void)removeObserver:(id)observer;

- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值