Android里面发消息可以用广播,也可以自己定义一套框架,比如eventbus,iOS也有自己原生的消息框架--NSNotificationCenter。
这里简单记录下怎么使用NSNotificationCenter类,直接贴代码:
//
// ViewController.m
// NotificationTest
//
// Created by Alex on 2017/3/26.
// Copyright © 2017年 alex. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[ defaultCenter] addObserver:self selector:@selector(notice:) name:@"notify1" object:nil];
[_mBtnSend addTarget:self action:@selector(sendNotify) forControlEvents:UIControlEventTouchUpInside];
[_mBtnRemove addTarget:self action:@selector(removeNotify) forControlEvents:UIControlEventTouchUpInside];
}
/** 发送通知*/
- (void)sendNotify {
NSLog(@"%s", "sendNotify");
[[NSNotificationCenter defaultCenter] postNotificationName:@"notify1" object:@"888"];
}
/** 注销通知*/
- (void)removeNotify {
NSLog(@"%s", "removeNotify");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/** 接受消息*/
- (void)notice:(NSNotification *)sender {
NSLog(@"%s", "接受到消息");
NSLog(@"%@", sender.object);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
打印记录
2017-03-27 12:02:03.198 NotificationTest[3623:308708] sendNotify
2017-03-27 12:02:03.200 NotificationTest[3623:308708]接受到消息
2017-03-27 12:02:03.200 NotificationTest[3623:308708] 888
2017-03-27 12:02:26.500 NotificationTest[3623:308708] removeNotify
[NSNotificationCenter defaultCenter] 调用这个方法是单例模式的,所以可以直接这么写
注意:如果添加了一个观察者作为接受消息的对象,那么销毁这个对象时需要注销掉这个观察者