通知中心-广播

本文介绍了一个使用Objective-C实现的广播机制案例。该案例通过创建广播中心并利用NSNotificationCenter进行广播消息的发送与接收,演示了如何定义广播发送者与接收者,并实现了循环广播的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

广播中心建立广播
收听者注册收听

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值