广播中心建立广播
收听者注册收听
int main(int argc, const char * argv[])
{
@autoreleasepool
{
//只做一次广播
/* Listener* l=[[Listener alloc]init];
[l wantToListen];
BJBoradcast* bj=[[BJBoradcast alloc]init];
[bj broadcast];
*/
//循环的广播
BJBoradcast* bj=[[BJBoradcast alloc]init];
[bj broadcastLooper];
Listener* l1=[[Listener alloc]init];
[l1 wantToListen];
Listener* l2=[[Listener alloc]init];
[l2 wantToListen];
[[NSRunLoop currentRunLoop]run];
}
return 0;
}
广播中心进行广播
@interface BJBoradcast : NSObject
-(void)broadcast;
-(void)broadcastLooper;
@end
@implementation BJBoradcast
-(void)broadcastLooper//启动一个定时器,循环的发送广播
{
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(broadcast) userInfo:nil repeats:YES];
}
//发送一次广播
-(void)broadcast
{
//1.取得通知中心
NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
static int i=0;
NSString* count=[NSString stringWithFormat:@”bcast %d”,i++];
NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:@”BJBoardcast”,@”name”,count,@”value”, nil];
//2.发送广播
[nc postNotificationName:@”BJBoradcast” object:self userInfo:dict];
//广播的频段,从哪发送过来的,self表示从当前自己的对象发送过来的
}
@end
收听者进行收听
@interface Listener : NSObject
-(void)wantToListen;
-(void)recvBcast:(NSNotification *)notify;
@end
@implementation Listener
-(void)wantToListen
{
//1.注册
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(recvBcast:) name:@”BJBoradcast” object:nil];
//只要有BJBoradcast广播,就调用self里面的recvBcast方法,第四个参数是接受某个频段的广播,一般为空
}
//2.真正的接收广播数据
-(void)recvBcast:(NSNotification *)notify
{
NSString* name=notify.name;
NSLog(@"notify is %@",notify);
}
@end