消息中心的使用

来源:互联网 发布:淘宝图片多少厘米 编辑:程序博客网 时间:2024/04/29 19:23

消息中心在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消息通知

    }

}



原创粉丝点击