您的位置:首页 > 移动开发 > IOS开发

iOS--Notification

2014-04-04 10:46 405 查看
Notification(消息中心)是iOS观察者模式的另一种实现,相比较KVO跟容易操作,Notification也可用于跨界面传值(传值小懒会再开一个模块),也是很常用的传值写法,废话不多说,上代码!

先创建RootViewController(根视图)、SecondViewController(第二个视图)。

RootViewController.m

- (void)viewDidLoad

{

[super viewDidLoad];

NSNotificationCenter *notice = [NSNotificationCenter defaultCenter];//启用消息中心

[notice addObserver:self selector:@selector(action:) name:@"color" object:nil];//添加观察者

UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 50, 50, 50)];

[self.view addSubview:button];

[button release];

[button setBackgroundColor:[UIColor redColor]];

[button addTarget:self action:@selector(toSecond) forControlEvents:UIControlEventTouchUpInside];

}

-(void)toSecond

{

SecondViewController *second = [[SecondViewController alloc]init];

[self presentViewController:second animated:YES completion:NULL];

[second release];

}

-(void)action:(NSNotification *)sender

{

[self.view setBackgroundColor:[UIColor orangeColor]];

NSLog(@"%@",sender);

}

SecondViewController.m

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view.

[self.view setBackgroundColor:[UIColor blueColor]];

UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 50, 50, 50)];

[self.view addSubview:button];

[button release];

[button setBackgroundColor:[UIColor redColor]];

[button addTarget:self action:@selector(toRoot) forControlEvents:UIControlEventTouchUpInside];

}

-(void)toRoot

{

NSNotificationCenter *notice = [NSNotificationCenter defaultCenter];//启用消息中心

// [notice postNotificationName:@"color" object:nil];

[notice postNotificationName:@"color" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"123",@"456", nil]];//发送请求及消息

[self dismissViewControllerAnimated:YES completion:NULL];

}

小懒习惯用mrc,所以在最后别忘了加上dealloc函数

-(void)dealloc

{

[[NSNotificationCenter defaultCenter]removeObserver:self name:@"color" object:nil];

[super dealloc];

}

很简单的小demo,当我们完成两次点击button后的界面切换时,会有字符串打印出来。

首先当我们要用到notification时要做个声明:

NSNotificationCenter *notice = [NSNotificationCenter defaultCenter];//启用消息中心

然后添加观察者,以name字段为key响应事件,一个对象可以添加多个观察者,可以有多个响应事件。

[notice addObserver:self selector:@selector(action:) name:@"color" object:nil];

最后在另外的界面也要先启用消息中心,然后发送请求即可:

[notice postNotificationName:@"color" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"123",@"456", nil]];

以“color”为关键字寻找对应观察者,userInfo为发送对象(即传值)。让我们回头在看看这个函数:

-(void)action:(NSNotification *)sender

{

[self.view setBackgroundColor:[UIColor orangeColor]];

NSLog(@"%@",sender);

}

这是观察者的响应函数,sender参数边包含了传递过来的值。

ok,已经讲完了,是不是特别简单!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: