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

ios开发之通知事件

2015-09-22 10:41 585 查看
每天学习一点点,总结一点点,成功从良好的习惯开始!

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

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

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

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

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.frame = CGRectMake(10, 10, 50, 50);
button.backgroundcolor = [UIColor bluecolor];
[self.view addSubview button];

//添加action
[button addTarget:self action:@selector(clickButton:) forControlEvents: UIControlEventTouchUpInside];

//添加观察者,监听通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(recEvent:)
name:@"notification" object:nil];        //name最好用宏定义,这里简单使用NSString

- (void)clickButton:(NSNotification *)notification
{
//当点击按钮的时候发送通知
[[NSNotificationCenter defaultCenter]
postNotificationName:@"notification" object:nil];  //object可以带一些自己感兴趣的值
}

- (void)recEvent:(NSNotification *)notification
{
//当收到通知的时候我们简单在这里打印一句话吧
NSLog(@“receive event”);
}

-(void)dealloc
{
[super dealloc];

//重写dealloc方法,移除观察者(至关重要)
[[NSNotificationCenter defaultCenter] removeObserver:self name:@“notification” object:nil];
//注意参数notificationObserver为要删除的观察者,一定不能 置为nil。

// 如果这有好多监听代理的
     //[[NSNotificationCenter defaultCenter] removeObserver:self];

}


注:以上代码纯手打,如有错误,多多包含!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: