OC中的通知

来源:互联网 发布:如何翻墙 知乎 编辑:程序博客网 时间:2024/05/29 10:43

上节课学习到了KVC和KVO,

而这次说的是通知

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

的消息。

首先初始化,有两种方法

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

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

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

    

    

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

    

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

    NSNotificationCenter *center = [NSNotificationCenterdefaultCenter];

    

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

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

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

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


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

- (id)init{

    

    

- (id)init{



   if (self  = [superinit]) {

       //注册监听者

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

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

        //3.接收通知的名字

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

        [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@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];

    

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

    [[NSNotificationCenterdefaultCenter]removeObserver:self ];

   NSLog(@"aa");

    

}




0 0