2。iOS基础知识—回顾

iOS基础知识整理之Notification Center

2018-11-07  本文已影响15人  郑知鱼
水始冰

Notification Center

概念

通过通知中心向所有注册观察者广播的信息容器
它是一个单例对象,允许当事情发生时通知一些对象,让对象作出相应反应。
它允许我们在低程度耦合的情况下,满足控制器与一个任意的对象进行通信的目的。
这种模式的基本特征是为了让其他的对象能够接收到某种事件传递过来的通知,主要使用通知名称来发送和接收通知。
基本上不用考虑其他影响因素,只需要使用同样的通知名称,监听该通知的对象(即观察者)再对通知做出反应即可。

优缺点

1.优点

2.缺点

使用方式

1.不传参数

发送通知


[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationWithoutParameter" object:nil];

监听


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

调用方法


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

2.使用object传递参数

发送通知


NSString *object = @"notiObject";

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationWithObject" object:object];

监听


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

调用方法


- (void)notiWithObject:(NSNotification *)notiication {

    id object = notiication.object;

    NSLog(@"Received the notification with object");

}

3.使用userInfo传递参数

发送通知


NSDictionary *userInfoDict = @{@"userInfo":@"130293739"};

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationWithUserInfo" object:nil userInfo:userInfoDict];

监听


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

调用方法


- (void)notiWithUserInfo:(NSNotification *)notiication {

    NSDictionary *userInfo = notiication.userInfo;

    NSLog(@"Received the notification with userInfo:%@",userInfo);

}

上一篇 下一篇

猜你喜欢

热点阅读