iOS 设计模式-NSNotificationCenter 通知中心

通知介绍

每一个应用程序都有一个通知中心(NSNotificationCenter)实例,专门负责协助不同对象之间的消息通信

任何一个对象都可以向通知中心发布通知(NSNotification),描述自己在做什么。

其他感兴趣的对象(Observer)可以申请在某个特定通知发布时(或在某个特定的对象发布通知时)收到这个通知

初始化通知中心

        // 初始化通知中心
        NSNotificationCenter *center =[NSNotificationCenter defaultCenter];

注册通知监听器

通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)

方法一:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
  • observer:监听器,即谁要接收这个通知
  • aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
  • aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知
  • anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知

方法二:

- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue                 usingBlock:(void (^)(NSNotification *note))block;
  • name:通知的名称
  • obj:通知发布者
  • block:收到对应的通知时,会回调这个block
  • queue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行

发布通知

通知中心(NSNotificationCenter)提供了相应的方法来帮助发布通知

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

发布一个notification通知,可在notification对象中设置通知的名称、通知发布者、额外信息等

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

发布一个名称为aName的通知,anObject为这个通知的发布者

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

发布一个名称为aName的通知,anObject为这个通知的发布者,aUserInfo为额外信息

取消注册通知监听器

通知中心不会保留(retain)监听器对象,在通知中心注册过的对象,必须在该对象释放前取消注册。否则,当相应的通知再次出现时,通知中心仍然会向该监听器发送消息。因为相应的监听器对象已经被释放了,所以可能会导致应用崩溃

•通知中心提供了相应的方法来取消注册监听器

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

一般在监听器销毁之前取消注册(如在监听器中加入下列代码):

- (void)dealloc {
  //[super dealloc];  非ARC中需要调用此句
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

实例代码

两个新闻机构(腾讯新闻、新浪新闻),每当发布新闻时,通知订阅了该新闻的用户。

新闻机构类 NewsCompany.h

//  新闻发布机构

#import <Foundation/Foundation.h>

@interface NewsCompany : NSObject
/**
 *  机构名称
 */
@property (nonatomic, copy) NSString *name;
@end

NewsCompany.m

#import "NewsCompany.h"

@implementation NewsCompany

@end

订阅者类

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject
/**
 * 姓名
 */
@property (nonatomic, copy) NSString *name;

- (void)newsCome:(NSNotification *)note;
@end

Person.m

#import "Person.h"
#import "NewsCompany.h"

@implementation Person

// 收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
- (void)newsCome:(NSNotification *)note
{
    // 通知的发布者
    NewsCompany *obj = note.object;

    NSLog(@"%@接收到了%@发出的通知,通知内容是:%@", self.name, obj.name, note.userInfo);
}

// 一般在监听器销毁之前取消注册
- (void)dealloc
{
//    [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

通知中心

main.m

#import <Foundation/Foundation.h>
#import "Person.h"
#import "NewsCompany.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        // 1.初始化机构
        NewsCompany *tx = [[NewsCompany alloc] init];
        tx.name = @"腾讯新闻";

        NewsCompany *sina = [[NewsCompany alloc] init];
        sina.name = @"新浪新闻";

        // 2.初始化2个人
        Person *zhangsan = [[Person alloc] init];
        zhangsan.name = @"张三";

        Person *lisi = [[Person alloc] init];
        lisi.name = @"李四";

        // 初始化通知中心
        NSNotificationCenter *center =[NSNotificationCenter defaultCenter];

        // 3.注册通知监听器
        // zhangsan只监听tx发出的junshi_news_come通知
        [center addObserver:zhangsan selector:@selector(newsCome:) name:@"junshi_news_come" object:nil];
        // lisi监听tx发的所有通知
        [center addObserver:lisi selector:@selector(newsCome:) name:nil object:tx];

        // 4.发布通知
        // tx发布了一则叫做junshi_news_come的通知
        [center postNotificationName:@"junshi_news_come"
                              object:tx
                            userInfo:@{@"title" : @"伊拉克战争停止了",
                                       @"intro" : @"伊拉克战争停止了.........."}];

        // sina发布了一则叫做junshi_news_come的通知
        [center postNotificationName:@"yule_news_come"
                              object:sina
                            userInfo:@{@"title" : @"6456456456456",
                                       @"intro" : @"7657567567567"}];

    }
    return 0;
}

运行结果:

时间: 2024-08-07 16:53:07

iOS 设计模式-NSNotificationCenter 通知中心的相关文章

iOS之NSNotificationCenter通知中心使用事项

其实这里的通知和之前说到的KVO功能很想,也是用于监听操作的,但是和KVO不同的是,KVO只用来监听属性值的变化,这个发送监听的操作是系统控制的,我们控制不了,我们只能控制监听操作,类似于Android中系统发送的广播,我们只能接受.但是通知就不一样了,他的监听发送也是又我们自己控制,我们可以在任何地方任何时机发送一个通知,类似于Android中开发者自己发送的广播.从这一点看来,通知的使用场景更为广泛了. 下面就来看一下例子: 还是护士和小孩的那个例子 Children.h [objc] vi

学习IOS开发UI篇--NSNotificationCenter通知中心

NSNotificationCenter 较之于 Delegate 可以实现更大的跨度的通信机制,可以为两个无引用关系的两个对象进行通信.NSNotificationCenter 的通信原理使用了观察者模式; 1. NSNotificationCenter 注册观察者对某个事件(以字符串命名)感兴趣,及该事件触发时该执行的 Selector 或 Block 2. NSNotificationCenter 在某个时机激发事件(以字符串命名) 3. 观察者在收到感兴趣的事件时,执行相应的 Selec

iOS生命周期 & 通知中心

笔记内容 学习笔记-段玉磊 Stanford course View Controller Lifecycle 这篇文是我记载Developing iOS 7 Apps公开课 第5课的笔记 UITextView Set its text and attributes via its NSMutableAttributedString 使用UITextView 要属性NSTextStorage类型 @property (nonatomic, readonly) NSTextStorage *tex

IOS NSNotification Center 通知中心的使用

通知中心,它是IOS程序内部的一种消息广播机制.通过它.能够实现无引用关系的对象之间的通信. 通知中心他是基于观察者模式,它仅仅能进行程序内部通信,不能跨应用程序进程通信.当通知中心接受到消息后会依据设置,将消息发送给订阅者,这里的订阅者能够有多个. 通知中心与代理模式类似,都能够实现多个对象间通信,通知中心能够将一个通知发送给多个监听者,而代理模式每一个对象仅仅能加入一个代理.但不管是那种模式,都是一种低耦合的设计,实现对象间的通信. 使用通知中心的步骤 1.注冊观察者对某个事件(以字符串命名

NSNotificationCenter 通知中心传值

1.NSNotification 这个类可以理解为一个消息对象,其中有三个成员变量. 这个成员变量是这个消息对象的唯一标识,用于辨别消息对象. @property (readonly, copy) NSString *name;   这个成员变量定义一个对象,可以理解为针对某一个对象的消息. @property (readonly, retain) id object;   这个成员变量是一个字典,可以用其来进行传值. @property (readonly, copy) NSDictionar

iOS 通知中心 NSNotificationCenter

iOS开发中,每个app都有一个通知中心,通知中心可以发送和接收通知. 在使用通知中心 NSNotificationCenter之前,先了解一下通知 NSNotification. NSNotification 可以理解为消息对象,包含三个成员变量,如下: @property (readonly, copy) NSString *name; @property (nullable, readonly, retain) id object; @property (nullable, readonl

通知中心 NSNotificationCenter 的简单使用方法

NSNotificationCenter(通知中心)   [注意]需再dealloc中移除观察者   获取通知中心单例对象 NSNotificationCenter *center=[NSNotificationCenter defaultCenter]; 常用方法: 1.注册观察者 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; 参数: ob

Notification Centers 通知中心

Notification Centers 通知中心 A notification center manages the sending and receiving of notifications. It notifies all observers of notifications meeting specific criteria. The notification information is encapsulated in NSNotification objects. Client o

通知中心NSNotification与委托的异同,需要注意的要点

调度表 通知中心保存了一个调度表,表的内容包括:通知观察者(必须存在).通知名称和通知发送者. 通知中心的调度表给观察者指定了对应的通知集,一个通知集是通知中心发出的通知的子集. 调度表入口有4种类型,如下表所示: (英文版说明) Notification name Notification sender Notification set specified Specified Specified Notifications with a particular name from a speci