前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >NSNotificationCenter 通知的使用方法详解你要知道的KVC、KVO、Delegate、Notification都在这里

NSNotificationCenter 通知的使用方法详解你要知道的KVC、KVO、Delegate、Notification都在这里

作者头像
WWWWDotPNG
发布2018-04-10 11:46:09
2.1K0
发布2018-04-10 11:46:09
举报
文章被收录于专栏:iOS技术杂谈iOS技术杂谈

你要知道的KVC、KVO、Delegate、Notification都在这里

转载请注明出处 https://cloud.tencent.com/developer/user/1605429

本系列文章主要通过讲解KVC、KVO、Delegate、Notification的使用方法,来探讨KVO、Delegate、Notification的区别以及相关使用场景,本系列文章将分一下几篇文章进行讲解,读者可按需查阅。

  • KVC 使用方法详解及底层实现
  • KVO 正确使用姿势进阶及底层实现
  • Protocol与Delegate 使用方法详解
  • NSNotificationCenter 通知使用方法详解
  • KVO、Delegate、Notification 区别及相关使用场景

NSNotificationCenter 通知的使用方法详解

NSNotificationCenter通知中心是iOS程序内部的一种消息广播的实现机制,可以在不同对象之间发送通知进而实现通信,通知中心采用的是一对多的方式,一个对象发送的通知可以被多个对象接收,这一点与我们前面讲解的KVO机制类似,KVO触发的回调函数也可以被对个对象响应,但代理模式delegate则是一种一对一的模式,委托对象只能有一个,对象也只能和委托对象通过代理的方式通信。

首先看一下比较重要的NSNotification类,这是通知中心的基础,通知中心发送的的通知都会封装成该类的对象进而在不同对象之间传递。其比较重要的属性和方法如下:

代码语言:javascript
复制
//通知的名称,有时可能会使用一个方法来处理多个通知,可以根据名称区分
@property (readonly, copy) NSNotificationName name;
//通知的对象,常使用nil,如果设置了值注册的通知监听器的object需要与通知的object匹配,否则接收不到通知
@property (nullable, readonly, retain) id object;
//字典类型的用户信息,用户可将需要传递的数据放入该字典中
@property (nullable, readonly, copy) NSDictionary *userInfo;

//下面三个是NSNotification的构造函数,一般不需要手动构造
- (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)) NS_DESIGNATED_INITIALIZER;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

NSNotification通知类本身很简单,需要着重理解的就是其三个属性,接下来看一下NSNotificationCenter通知中心,通知中心采用单例的模式,整个系统只有一个通知中心,通过如下代码获取:

代码语言:javascript
复制
[NSNotificationCenter defaultCenter]

再看一下通知中心的几个核心方法:

代码语言:javascript
复制
/*
注册通知监听器,只有这一个方法
observer为监听器
aSelector为接到收通知后的处理函数
aName为监听的通知的名称
object为接收通知的对象,需要与postNotification的object匹配,否则接收不到通知
*/
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;

/*
发送通知,需要手动构造一个NSNotification对象
*/
- (void)postNotification:(NSNotification *)notification;

/*
发送通知
aName为注册的通知名称
anObject为接受通知的对象,通知不传参时可使用该方法
*/
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;

/*
发送通知
aName为注册的通知名称
anObject为接受通知的对象
aUserInfo为字典类型的数据,可以传递相关数据
*/
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

/*
删除通知的监听器
*/
- (void)removeObserver:(id)observer;

/*
删除通知的监听器
aName监听的通知的名称
anObject监听的通知的发送对象
*/
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

/*
以block的方式注册通知监听器
*/
- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

接下来举一个栗子,和之前delegate的栗子相同,只不过这里使用通知来实现,依旧是两个页面,ViewControllerNextViewController,在ViewController中有一个按钮和一个标签,点击按钮跳转到NextViewController视图中,NextViewController中包含一个输入框和一个按钮,用户在完成输入后点击按钮退出视图跳转回ViewController并在ViewController的标签中展示用户填写的数据,接下来看一下代码:

代码语言:javascript
复制
//ViewController部分代码

- (void)viewDidLoad
{
    //注册通知的监听器,通知名称为inputTextValueChangedNotification,处理函数为inputTextValueChangedNotificationHandler:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputTextValueChangedNotificationHandler:) name:@"inputTextValueChangedNotification" object:nil];

}

//按钮点击事件处理器
- (void)buttonClicked
{
    //按钮点击后创建NextViewController并展示
    NextViewController *nvc = [[NextViewController alloc] init];
    [self presentViewController:nvc animated:YES completion:nil];
}

//通知监听器处理函数
- (void)inputTextValueChangedNotificationHandler:(NSNotification*)notification
{
    //从userInfo字典中获取数据展示到标签中
    self.label.text = notification.userInfo[@"inputText"];
}

- (void)dealloc
{
    //当ViewController销毁前删除通知监听器
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"inputTextValueChangedNotification" object:nil];
}


//NextViewController部分代码
//用户完成输入后点击按钮的事件处理器
- (void)completeButtonClickedHandler
{
    //发送通知,并构造一个userInfo的字典数据类型,将用户输入文本保存
    [[NSNotificationCenter defaultCenter] postNotificationName:@"inputTextValueChangedNotification" object:nil userInfo:@{@"inputText": self.textField.text}];
    //退出视图
    [self dismissViewControllerAnimated:YES completion:nil];
}

代码比较简单不再给出相关运行截图了,不难发现NSNotificationCenter的使用步骤如下:

  • 1、在需要监听某通知的地方注册通知监听器 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputTextValueChangedNotificationHandler:) name:@"inputTextValueChangedNotification" object:nil];
  • 2、实现通知监听器的回调函数 - (void)inputTextValueChangedNotificationHandler:(NSNotification*)notification { self.label.text = notification.userInfo[@"inputText"]; }
  • 3、在监听器对象销毁前删除通知监听器 - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:@"inputTextValueChangedNotification" object:nil]; }
  • 4、如有通知需要发送,使用NSNotificationCenter发送通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"inputTextValueChangedNotification" object:nil userInfo:@{@"inputText": self.textField.text}];

对于删除监听器这一步骤在iOS9以后似乎变得不那么重要,iOS9开始不再对已经销毁的监听器发送通知,当监听器对象销毁后发送通知也不会造成野指针错误,这一点比KVO更加安全,KVO在监听器对象销毁后仍会触发回调函数就可能造成野指针错误,因此使用通知也就可以不手动删除监听器了,但如果需要适配iOS9之前的系统还是需要养成手动删除监听器的习惯。

上面的栗子很简单,但有一点是需要强调的,我们在NextViewController中发送的通知是在main线程中发送的,因此ViewController中的监听器回调函数也会在main线程中执行,因此我们在监听器回调函数中修改UI不会产生任何问题,但当通知是在其他线程中发送的,监听器回调函数很有可能就是在发送通知的那个线程中执行,我们知道UI的更新必须在主线程中执行,这个时候就需要注意,如果通知监听器回调函数有需要更新UI的代码,需要使用GCD放在主线程中执行,代码如下:

代码语言:javascript
复制
//NextViewController发送通知的代码修改为如下代码:
- (void)completeButtonClickedHandler
{
    //使用GCD获取一个非主线程的线程用于发送通知
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"inputTextValueChangedNotification" object:nil userInfo:@{@"inputText": self.textField.text}];
    });
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//ViewController通知监听器的回调函数修改为如下代码:
- (void)inputTextValueChangedNotificationHandler:(NSNotification*)notification
{
    //使用GCD获取主线程并更新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        self.label.text = notification.userInfo[@"inputText"];
    });
    //如果不在主线程更新UI很有可能无法正确执行
    //self.label.text = notification.userInfo[@"inputText"];
}

很多时候我们使用的是第三方框架发送的通知,或是系统提供的通知,我们无法预知这些通知是否是在主线程中发送的,为了安全起见最好在需要更新UI时使用GCD将更新的逻辑放入主线程执行。

系统提供了很多各式各样的通知,比如当我们要实现IM即时通讯类app的聊天页面输入框时就可以使用系统键盘发出的通知,相关通知有UIKeyboardWillShowNotificationUIKeyboardWillHideNotification,顾名思义一个是键盘即将展示,一个是键盘即将退出的通知,接下来给一个简单的实现:

代码语言:javascript
复制
#import "ViewController.h"

#define ScreenWidth [[UIScreen mainScreen] bounds].size.width
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height

@interface ViewController ()

@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UITextField *textField;

@end

@implementation ViewController

@synthesize containerView = _containerView;
@synthesize textField = _textField;

- (instancetype)init
{
    if (self = [super init])
    {
        self.view.backgroundColor = [UIColor whiteColor];

        //创建一个容器View可自定义相关UI
        self.containerView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 60, ScreenWidth, 60)];
        self.containerView.backgroundColor = [UIColor redColor];
        [self.view addSubview:self.containerView];
        
        //用户输入的UITextField
        self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, ScreenWidth - 40, 40)];
        self.textField.placeholder = @"input...";
        self.textField.backgroundColor = [UIColor greenColor];
        [self.containerView addSubview:self.textField];
        
        [self.view addSubview:self.containerView];
        
        //添加一个手势点击空白部分后收回键盘
        UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView)];
        [self.view setMultipleTouchEnabled:YES];
        [self.view addGestureRecognizer:gesture];

    }
    return self;
}

- (void)viewDidLoad
{
    //注册UIKeyboardWillShowNotification通知,监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //注册UIKeyboardWillHideNotification通知,监听键盘回收事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

//自定义手势响应处理器
- (void)tapView
{
    //触发收回键盘事件
    [self.textField resignFirstResponder];
}

//UIKeyboardWillShowNotification通知回调函数
- (void)keyboardWillShow:(NSNotification*)notification
{
    //获取userInfo字典数据
    NSDictionary *userInfo = [notification userInfo];
    //根据UIKeyboardBoundsUserInfoKey键获取键盘高度
    float keyboardHeight = [[userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    //获取键盘弹出的动画时间
    NSTimeInterval animationDuration;
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    //自定义动画修改ContainerView的位置
    [UIView animateWithDuration:animationDuration animations:^{
        self.containerView.frame = CGRectMake(0, ScreenHeight - keyboardHeight - self.containerView.frame.size.height, self.containerView.frame.size.width, self.containerView.frame.size.height);
    }];

}

//UIKeyboardWillHideNotification通知回调函数
- (void)keyboardWillHide:(NSNotification*)notification
{
    //获取动画执行执行时间
    NSValue *animationDurationValue = [[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    //自定义动画修改ContainerView的位置
    [UIView animateWithDuration:animationDuration animations:^{
        self.containerView.frame = CGRectMake(0, ScreenHeight - self.containerView.frame.size.height, self.containerView.frame.size.width, self.containerView.frame.size.height);
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

@end

最终效果如下图所示(GIF下载可能有点慢):

丝滑键盘

备注

由于作者水平有限,难免出现纰漏,如有问题还请不吝赐教。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.10.13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 你要知道的KVC、KVO、Delegate、Notification都在这里
    • NSNotificationCenter 通知的使用方法详解
      • 备注
      相关产品与服务
      容器服务
      腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档