NSNotificationCenter使用

来源:互联网 发布:人工智能创业公司 编辑:程序博客网 时间:2024/05/16 18:34

NSNotificationCenter使用

NSNotificationCenter 是专门供程序中不同类之间的消息通信而设置
分为以下几个步骤:
1、注册通知:即要在什么地方接收消息
2、移除通知:要与注册通知保持成对出现,避免出现未销毁通知导致程序崩溃
3、发送通知,在别的类发送通知,从而使得注册通知的类可以接收到信号,执行相关的方法

//注册通知[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myTest:) name:@"testNotifiName" object:nil];// 参数介绍:    addObserver:观察者,即在什么地方接收通知;    selector:收到通知后调用何种方法;    name:通知的名字,也是通知的唯一标识,编译器就通过这个找到通知的。
//发送通知:[NSNotificationCenter defaultCenter] postNotificationName:@"testNotifiName" object:@"vic haha"];//参数介绍:postNotificationName:通知的名字,也就是通知的唯一标识,编译器就是通过这个找到通知的。object:传递的参数
//在第一个界面FirstViewController注册通知@implementation FirstViewController-(void)viewDidLoad{    [super viewDidLoad];    //注册通知    [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:@"vic" object:nil];}-(void)test:(NSNotification *)notification{    //获取通知所传递的参数    id obj = [notification object];}-(void)dealloc {    //移除通知    [NSNotificationCenter defaultCenter] removeObserver:self name:@"vic" object :nil];}
//在第二个界面发送通知-(void)click{    [NSNotificationCenter defaultCenter] postNotificationName:@"vic" object:@"hahaha"];}

举例:

// 注册键盘升启关闭的消息// 1、升启[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];// 2、降下[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
0 0