首页 > 代码库 > OC通知中心
OC通知中心
//通知中心广播站建立 //1.head.h #import <Foundation/Foundation.h> @interface BJBroadcast : NSObject -(void)sendBroadCast; -(void)sendBroadCastLoop; @end //2.implementation #import "BJBroadcast.h" @implementation BJBroadcast -(void)sendBroadCastLoop { //每隔一秒发送一次广播消息 [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(sendBroadCast) userInfo:nil repeats:YES]; } -(void)sendBroadCast { //创建广播站 NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter]; static NSUInteger i; NSString *count=[[NSString alloc]initWithFormat:@"broadCount %ld",i++]; NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"BJBroadcast",@"Name",count,@"Timer", nil]; [notificationCenter postNotificationName:@"BJBroadcast" object:self userInfo:dic]; [count release]; [dic release]; } @end //广播接受者 //1.head.h @interface Listener : NSObject -(void)wantTolistenBroadcast; @end //implementation #import "Listener.h" @implementation Listener -(void)wantTolistenBroadcast { [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Broadcast:) name:@"BJBroadcast" object:nil]; /*#program mark 1.addObserver:表示谁对通知中心发出的信息感兴趣 2.selector:收到该感兴趣信息的处理函数 3.name:对什么名字的广播感兴趣 4.object:对谁发出的广播感兴趣,nil表示对任何人发出的广播都感兴趣 */ } -(void)Broadcast:(NSNotification *)notification { NSLog(@"%@",notification); } @end //main #import <Foundation/Foundation.h> #import "BJBroadcast.h" #import "Listener.h" int main(int argc, const char * argv[]) { @autoreleasepool { Listener *aListener=[[Listener alloc]init]; [aListener wantTolistenBroadcast]; BJBroadcast *Bj=[[BJBroadcast alloc]init]; [Bj sendBroadCastLoop]; [[NSRunLoop currentRunLoop] run];//一定要添加该方法,否则无法循环 [aListener release]; [Bj release]; } return 0; }
本文出自 “网络学习总结” 博客,请务必保留此出处http://8947509.blog.51cto.com/8937509/1555031
OC通知中心
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。