第一个页面进来后,先注册监听
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//先在通知中心注册
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:NOTIFICATION_MESSAGE object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:YES];
// [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)doSomething:(NSNotification *)notification
{
//接受消息
NSDictionary *Info = [notification userInfo];
//输出收到的信息
NSLog(@“消息收到:%@", Info[@"notification"]);
}
第二个页面进来后点击button 然后发消息
@implementation ChatViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self initContentView];
}
- (void)initContentView
{
UIButton *_commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 179, kDEVICEWIDTH-30, 45)];
_commitBtn.backgroundColor = [UIColor grayColor];
[_commitBtn addTarget:self action:@selector(commitClick) forControlEvents:UIControlEventTouchUpInside];
[_commitBtn setTitle:@"发消息" forState:UIControlStateNormal];
_commitBtn.titleLabel.textColor = [UIColor whiteColor];
_commitBtn.layer.cornerRadius = 4;
[self.view addSubview:_commitBtn];
}
- (void)commitClick
{
[self sendMessage];
}
#pragma mark - NSNotification method
-(void)sendMessage
{
//把要发送的信息放入字典中
NSDictionary *message = @{@"notification" : @“NSNotification消息测试通过!”};
//创建通知对象
NSNotification * notification = [NSNotification notificationWithName:NOTIFICATION_MESSAGE object:self userInfo:message];
//向通知中心发送消息(发布消息)
//[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_MESSAGE object:nil];
//向通知中心发送消息(发布消息)
[[NSNotificationCenter defaultCenter] postNotification:notification];
}