NSNotificationCenter 通知的使用方法详解

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

转载请注明出处 http://www.jianshu.com/p/f6224f075437

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

NSNotificationCenter 通知的使用方法详解

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

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

//通知的名称,有时可能会使用一个方法来处理多个通知,可以根据名称区分
@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通知中心,通知中心采用单例的模式,整个系统只有一个通知中心,通过如下代码获取:

[NSNotificationCenter defaultCenter]

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

/*
注册通知监听器,只有这一个方法
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的标签中展示用户填写的数据,接下来看一下代码:

//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放在主线程中执行,代码如下:

//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,顾名思义一个是键盘即将展示,一个是键盘即将退出的通知,接下来给一个简单的实现:

#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下载可能有点慢):

丝滑键盘

备注

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容