OC中的通知

上节课学习到了KVC和KVO,

而这次说的是通知

通知单是一种发送给一个或者多个观察者,用来通知其在程序中发生某个时间

的消息。

首先初始化,有两种方法

/初始化一个通知(NSNotification)的实例对象

    //name:表示通知的名称         object:通知的发起人

    NSNotification *notification1 = [NSNotification notificationWithName:@"通知名称1" object:self];

    

    

    NSNotification *notification2 = [NSNotification notificationWithName:@"通知名称2" object:self userInfo:@{@"content":@"hello world"}];

    

    //通知中心   单例类,拿到通知中心的单例

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

    

    //建立通知的发送机制,如下:

//    1.注册监听者,并实现在需要的时候回调方法

//    2.在需要的时候,被监听者的对象去到通知中心发送消息

//    3.“dealloc”方法中移除通知


1.注册监听者,在你想要的类.m文件中初始化init方法

- (id)init{

    

    

- (id)init{



    if (self  = [super init]) {

        //注册监听者

        //1.要去接收通知的对象

        //2.接收通知要回调的相应的方法

        //3.接收通知的名字

        //4.发起通知的对象,一般不需要知道,nil

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"通知名称2" object:nil];

        

    }

    

    return  self;

    

}

2.监听到通知后回调方法

/监听到通知后回调的方法



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



    NSLog(@"什么是useInfo = %@",notification.userInfo);

}


3.移除监听者

//移除监听者


- (void)dealloc{

//移除某个通知的监听者

    //[[NSNotificationCenter defaultCenter] removeObserver:self name:@"通知名称2" object:nil];

    

  //移除所有通知的监听者

    [[NSNotificationCenter defaultCenter]removeObserver:self ];

    NSLog(@"aa");

    

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值