美文网首页
OC 消息发送--通知

OC 消息发送--通知

作者: dicesc | 来源:发表于2016-07-16 13:56 被阅读345次

通知介绍

  1. Notification:观察者模式, 通常发送者和接收者的关系是间接的多对多关系。消息的发送者告知接收者事件已经发生或者将要发送,仅此而已,接收者并不能反过来影响发送者的行为

  2. // 发送通知用 post 接收通知用 add observer 即为监听该通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"huoying"
    object:
    userInfo: ];所有信息放入userInfo中

  3. // 让控制器成为监听者
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(keyboardWillChangeFrame:)
    name:@"huoying" object:nil];

warning 一定不要忘记移除 监听者
  • (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }

通知的代码示例

person类

@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
-(void)didReceiveNotification:(NSNotification *)noti;
@end

@implementation Person
-(void)didReceiveNotification:(NSNotification *)noti {

NSDictionary *dict = noti.userInfo;

Person *p = dict[@"person"];

Company *c = dict[@"company"];

NSLog(@"%@, 订阅了 %@, %@ 更新了!!!",p.name, c.name, c.videoName);

}

-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

主方法添加监听者

// 创建两个人 对象
Person p1 = [Person new];
p1.name = @"张三";
Person p2 = [Person new];
p2.name = @"李四";
// 1. 添加监听者
// 张三, 监听了 火影忍者
/

addObserver : 监听者
selector : 监听者, 所需要具有的方法, 当监听者接收到通知的时候, 会调用
name : 通知的名称
object : 消息的发送者, 可以传递为nil
*/
[[NSNotificationCenter defaultCenter] addObserver:p1
selector:@selector(didReceiveNotification:)
name:@"huoying"
object:tudouNinja];
// 李四, 监听了 屌丝男士
[[NSNotificationCenter defaultCenter] addObserver:p2
selector:@selector(didReceiveNotification:)
name:@"Diaosi"
object:nil];

发送通知

// 2. 在适当时候 , 发出通知
// 火影忍者的更新
[[NSNotificationCenter defaultCenter] postNotificationName:@"huoying"
object:tudouNinja
userInfo:@{@"person":p1, @"company": tudouNinja}];

// 屌丝男士更新
[[NSNotificationCenter defaultCenter] postNotificationName:@"Diaosi"
object:souhuDiaosi
userInfo:@{@"person":p2, @"company": souhuDiaosi}];

相关文章

  • OC 消息发送--通知

    通知介绍 Notification:观察者模式, 通常发送者和接收者的关系是间接的多对多关系。消息的发送者告知接收...

  • iOS消息机制相关

    (1)OC中给nil对象发送消息程序是否会crash? OC向nil发送消息,是不会崩溃的。 OC的函数调用都是通...

  • iOS消息机制相关

    OC中给nil对象发送消息程序是否会crash? OC想nil发送消息,是不会崩溃的。 OC的函数调用都是通过ob...

  • 2018-04-03-Runtime消息发送

    要想一探消息发送的究竟,就不得不使用Rumtime,OC的实质就是消息的发送,接下来我们将简单的OC代码以消息发送...

  • 消息发送机制和运行时

    消息发送机制定义 OC的函数调用称为消息发送。OC的消息发送属于动态调用过程。即在编译的时候并不能决定真正调用哪个...

  • 常用设计模式

    通知 NSNotification 通知由消息中心发送消息中心在整个工程中有且只有一个消息中心可以发送多条消息 可...

  • runtime 消息机制简析

    runtime 消息机制消息机制可以简单分为三个方面:消息发送、动态方法解析、消息转发一.消息发送oc 中所有的方...

  • runtime消息发送和消息转发

    1.消息发送 消息发送举例:下面这个OC代码 [person read:book]; 会被编译成: objc_ms...

  • Objective-C runtime机制(2)——消息机制

    当我们用中括号[]调用OC函数的时候,实际上会进入消息发送和消息转发流程: 消息发送(Messaging),run...

  • iOS 2019年2月学习记录

    消息发送与转发1.1 简介OC的消息机制是通过runtime实现的,消息发送是通过selector快速查找IMP的...

网友评论

      本文标题:OC 消息发送--通知

      本文链接:https://www.haomeiwen.com/subject/nclujttx.html