iOSObjective-C之代理协议通知iOS日常须知

IOS中通知中心(NSNotificationCenter)的使

2016-07-20  本文已影响25849人  tanlon

NSNotification 是iOS中一个调度消息通知的类,采用单例模式设计,在程序中实现传值、回调等地方应用很广。

一、了解几个相关的类


1、NSNotification

这个类可以理解为一个消息对象,其中有三个成员变量。

这个成员变量是这个消息对象的唯一标识,用于辨别消息对象。

@property (readonly, copy) NSString *name;

这个成员变量定义一个对象,可以理解为针对某一个对象的消息。

@property (readonly, retain) id object;

这个成员变量是一个字典,可以用其来进行传值。

@property (readonly, copy) NSDictionary *userInfo;

NSNotification的初始化方法:

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo;

+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;

+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

注意:官方文档有明确的说明,不可以使用init进行初始化

2、NSNotificationCenter

这个类是一个通知中心,使用单例设计,每个应用程序都会有一个默认的通知中心。用于调度通知的发送的接受。

添加一个观察者,可以为它指定一个方法,名字和对象。接受到通知时,执行方法。

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

发送通知消息的方法

- (void)postNotification:(NSNotification *)notification;

- (void)postNotificationName:(NSString *)aName object:(id)anObject;

- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

移除观察者的方法

- (void)removeObserver:(id)observer;

- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;

几点注意:

1、如果发送的通知指定了object对象,那么观察者接收的通知设置的object对象与其一样,才会接收到通知,但是接收通知如果将这个参数设置为了nil,则会接收一切通知。

2、观察者的SEL函数指针可以有一个参数,参数就是发送的死奥西对象本身,可以通过这个参数取到消息对象的userInfo,实现传值。


二、通知的使用流程


1.通知的创建与发送

在需要发送通知的界面中创建通知

/** 返回到上个界面 */

- (IBAction)back:(id)sender {

// 1.添加字典, 将数据包到字典中

NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@"小明",@"name",@"111401",@"number", nil];

// 2.创建通知

NSNotification *notification =[NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];

// 3.通过 通知中心 发送 通知

[[NSNotificationCenter defaultCenter] postNotification:notification];

[self dismissViewControllerAnimated:YES completion:nil];

}

2.通知的接收

在需要接收的控制器中注册通知监听者,将通知发送的信息接收

- (void)viewDidLoad {

[super viewDidLoad];

// 1.注册通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"InfoNotification" object:nil];

}

// 2.实现收到通知触发的方法

- (void)InfoNotificationAction:(NSNotification *)notification{

NSLog(@"%@",notification.userInfo);

NSLog(@"---接收到通知---");

}

3.通知的移除

移除通知:removeObserver:和removeObserver:name:object:

其中,removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。

这个比较简单,直接调用该方法就行。例如:

[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];

注意参数notificationObserver为要删除的观察者,一定不能置为nil。

上一篇 下一篇

猜你喜欢

热点阅读