IOS 通知(实现及时聊天接受消息的现实)

为什么要用通知?

传递一个变化的数值。

例子

//接受消息
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    
    NSLog(@"%@说:%@",message.from,message.body);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"didREceiveMessage" object:nil userInfo:@{@"message":message}];
    
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    //设置广播内容
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          message.body, @"ThemeName", nil];
    //将内容封装到广播中 给ios系统发送广播
    [nc postNotificationName:@"getmessage" object:self userInfo:dict];// getmessage频道
}




 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    // 成为听众一旦有广播就来调用self recvBcast:函数
    [nc addObserver:self selector:@selector(recvBcast:) name:@"getmessage" object:nil];




- (void) recvBcast:(NSNotification *)notify
{
    static int index;
    NSLog(@"recv bcast %d", index++);
    NSDictionary *dict = [notify userInfo];
    NSString *getmessageTemp = [dict objectForKey:@"ThemeName"];
    NSLog(@"name的值:%@",getmessageTemp);
    [self.meassage addObject:getmessageTemp];
    [self.tView reloadData];
}
原文地址:https://www.cnblogs.com/penger/p/4481579.html