NSNotificationCenter介绍

来源:互联网 发布:tcp默认端口号 编辑:程序博客网 时间:2024/06/04 23:24
   

          通知中心是 Foundation 框架的一个子系统,它向应用程序中注册为某个事件观察者的所有对象广播消息(即通知)。(从编程角度而言,它是 NSNotificationCenter 类的实例)。该事件可以是发生在应用程序中的任何事情,例如进入后台状态,或者用户开始在文本栏中键入。通知是告诉观察者,事件已经发生或即将发生,因此让观察者有机会以合适的方式响应。通过通知中心来传播通知,是增加应用程序对象间合作和内聚力的一种途径。


     任何对象都可以观察通知,但要做到这一点,该对象必须注册,以接收通知。在注册时,它必须指定选择器,以确定由通知传送所调用的方法;方法签名必须只有一个参数:通知对象。注册后,观察者也可以指定发布对象。

(以上是官方文档中的解释)


    通知中心包括两个重要的类:

  (1)NSNotificationCenter: 实现NSNotificationCenter的原理是一个观察者模式,获得NSNotificationCenter的方法只有一种,那就是[NSNotificationCenter defaultCenter] ,通过调用静态方法defaultCenter就可以获取这个通知中心的对象了,而NSNotificationCenter是一个单例模式,而这个通知中心的对象会一直存在于一个应用的生命周期。

   (2) NSNotification: 这是消息携带的载体,通过它,可以把消息内容传递给观察者。

 (3)一个NSNotificationCenter可以有许多的通知消息NSNotification,对于每一个NSNotification可以有很多的观察者Observer来接收通知。

通过上面的介绍可以知道,通过通知中心也可以实现不同类之间的参数传递。

注意当接受到消息后,不想再收到消息了,要把observer删除remove。

下面介绍如何使用(具体解释看文档)。

(1)NSNotification :用于创建传递的消息

初始化通知的消息

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo NS_AVAILABLE(10_6,4_0);


- (id)init;


创建通知消息

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

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


获得通知消息的内容

- (NSString *)name;

- (id)object;

- (NSDictionary *)userInfo;

(2)NSNotificationCenter :用于发送消息

初始化

- (instancetype)init;


获得通知

+ (instancetype)defaultCenter;

管理通知

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

- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))blockNS_AVAILABLE(10_6,4_0);

- (void)removeObserver:(id)observer;

- (void)removeObserver:(id)observer 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;



0 0
原创粉丝点击