消息中心的使用

消息中心在IOS中经常被用到。

当一个某个条件被满足的时候,就可以使用消息中心把消息抛出。

如果满足某些条件时进行简单的通知抛出,则使用- (void)postNotification:(NSNotification *)notification

如果满足某些条件之后进行抛出并希望附带当前环境下的值,则使用- (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo,把值塞进useInfo中进行传递。

在相应地方进行通知的捕获和处理,使用- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender

一般来说,在捕获的地方对通知都使用统一的处理(SEL)notificationSelector,其代码中使用switch语句来分别处理不同的通知,使代码整齐。

最后,需要释放掉相应的通知,使用[[NSNotificationCenter defaultCenter] removeObserver:someObserver];


抛出通知:

[[NSNotificationCenter defaultCenter]postNotificationName:@"test1" object:self userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithDouble:Time] forKey:@"TEST"]];

注册通知并做响应:

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


处理方法

- (void)didReceiveNotification:(NSNotification*)aNoti

{

    NSString* name = aNoti.name;

    if([name isEqualToString:@"test1"]){

       NSLog(@"test:%@",[[aNoti userInfo] objectForKey:@"TEST"]);

      [[NetworkClock sharedNetworkClock] finishAssociations];//释放test1消息通知

    }

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值