ios消息机制NSNotification和android的BroadcastReceiver广播机制是一样的,其作用主要是像特定的对象发送特定的消息,接收消息的页面需要先在消息中心NSNotificationCenter注册,起到监听页面动态的作用,下面是iOS消息机制的简单案例,一看就懂!
#import "ListViewController.h"
@interface ListViewController ()
@end
@implementation ListViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
/**
* 此sendMsg方法为点击事件,点击发送按钮发送消息
* 参数一:name表示发送消息的标示,用于区分消息类型,如聊天信息,新闻提醒等等,可以随便取名字,这里为"msg"聊天消息
* 参数二:object表示发送的消息内容,可以为任何对象
* 参数三:userInfo为NSDictionary字典类型,可以将一个model对象转化为字典类型,
* 例如向“username”为“zhangshan”的用户发送hello信息
*/
- (IBAction)sendMsg:(UIButton *)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"msg" object:@"hello!" userInfo:@{@"username":@"zhangsan"}];
}
@endNSNotificationCenter对象使用postNotificationName方法将“hello”信息发送给了“zhangsan”的用户,那么如果zhangsan的用户登录进入了聊天界面,该如何接收到别人发送过来的hello信息呢?请看下面的例子。
#import "DetailViewController.h"
@interface DetailViewController ()
@end
@implementation DetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
//页面加载时NSNotificationCenter便向消息中心注册,监听前面定义的name为msg表示的消息,object为nil就好
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"msg" object:nil];
}
//接收消息的方法
-(void)receiveNotification:(NSNotification *)notification{
//获取username用户名
NSString *username = [[notification userInfo] objectForKey:@"username"];
//如果name标示为“msg”,并且用户名为“zhangsan”才能接收到消息,其他用户则接收不到消息
if ([[notification name] isEqualToString:@"msg"] && [username isEqualToString:@"zhangsan"]) {
//以下的object是获取
self.getLabel.text = [NSString stringWithFormat:@"接收到的消息: %@", [notification object]];
}
}
@endnotification对象主要页面取值的。
[notification name] 获取消息标示。
[notification userInfo] 获取消息model的字典类型,里面可以封装用户信息,发送给谁。
[notification object] 获取消息具体内容。