ios开发之通知事件

每天学习一点点,总结一点点,成功从良好的习惯开始!

 

昨天学习了ios开发中的关于通知事件的一些东西,在这里简单总结下,仅供初学者学习,更多的是怕我自己忘了,咩哈哈~~~~

通知(notification),顾名思义就是两个东西之间的通信,(A通知B或者B通知A),当A发生某个动作时向B发送通知,B监听这个事件,如果B监听到此事件了,就开始做某些事。

下面咱们开始从具体实例开始说吧!!!!

首先我们先创建一个按钮,A点击按钮来触发某个事件,发送通知,B收到通知后开始做某些事情。就是这么简单,下面来看下代码的实现

 1 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 2 
 3 button.frame = CGRectMake(10, 10, 50, 50);
 4 button.backgroundcolor = [UIColor bluecolor];
 5 [self.view addSubview button];
 6 
 7 //添加action
 8 [button addTarget:self action:@selector(clickButton:) forControlEvents: UIControlEventTouchUpInside];
 9 
10 //添加观察者,监听通知
11 [[NSNotificationCenter defaultCenter] addObserver:self
12     selector:@selector(recEvent:)
13     name:@"notification" object:nil];        //name最好用宏定义,这里简单使用NSString
14 
15 
16 
17 - (void)clickButton:(NSNotification *)notification
18 {
19     //当点击按钮的时候发送通知  
20    [[NSNotificationCenter defaultCenter]
21     postNotificationName:@"notification" object:nil];  //object可以带一些自己感兴趣的值
22 }
23 
24 
25 - (void)recEvent:(NSNotification *)notification
26 {
27     //当收到通知的时候我们简单在这里打印一句话吧
28     NSLog(@“receive event”);
29 }
30 
31 -(void)dealloc
32 {
[super dealloc];
33     //重写dealloc方法,移除观察者(至关重要) 
34 [[NSNotificationCenter defaultCenter] removeObserver:self name:@“notification” object:nil];
//注意参数notificationObserver为要删除的观察者,一定不能 置为nil。
35
// 如果这有好多监听代理的
     //[[NSNotificationCenter defaultCenter] removeObserver:self];
    }

 

注:以上代码纯手打,如有错误,多多包含!!!!!

posted @ 2015-09-22 10:41  simle、Mars  阅读(489)  评论(0)    收藏  举报