通知中心NSNotificationCenter

来源:互联网 发布:mysql基本语句向左向右 编辑:程序博客网 时间:2024/05/07 05:30
A,发送消息。-(void)broadcastLooper{    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(boardcast) userInfo:nil repeat:YES];}-(void)boardcast{    NSNotification* nc = [NSNotification defaultCenter];static int i;NSString* count = [NSString stringWithFormat:@"bcast %d", i++];    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:@"BJ boardcast", @"name",count, @"Value",nil];[nc postNodificationName:@"BJBoardcast" object:self userInfo:dict];}B,接收消息。-(void)wantToListen{    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvBcast:)name:@"BJBoardcast" object:nil];}-(void)recvBcast:(NSNotification*)notify{    NSLog(@"notify is %@",notify);}C,调用接听广播。Listener* l = [[Listener alloc] init];[l wantToListen];BJBoardcast* bj = [[BJBoardcast alloc] init];[bj boardcast];

总结:当只有一条消息时,听众应该先打开耳朵听,当广播发送完消息后,听众就会立马调用自己注册的那个回调函数.(非常重要!如果先发送,再收听.那么就会接收不到信息!!!也就是不会触发回调函数)



0 0