美文网首页
第五节:关于通知介绍

第五节:关于通知介绍

作者: 清杨程 | 来源:发表于2018-09-11 18:58 被阅读5次

    ———————————————  main.m文件——————————————— 

    #import 

    #import "Teacher.h"

    #import "Student.h"

    intmain(intargc, constchar* argv[]) {

     @autoreleasepool{

     //第一通知的发布者

     Teacher*tea = [[Teacheralloc] init];

     //第二通知的监听者

     Student*stu = [[Studentalloc] init];

     //第四获取NSNotificationCenter对象

     NSNotificationCenter*notification = [NSNotificationCenterdefaultCenter];

     //第五监听通知

     //参数1:要监听的对象

     //参数2:该对象的哪个方法用来监听这个通知

     //参数3:被监听通知的名称

     //参数4:发布通知的对象

     //1》如果没有指定参数3(即参数三为nil),但指定定了参数4为tea,那么凡事tea对戏那个发布的所有通知tea都会监听到。

     //2》如果指定了参数3,但没指定参数4,那么无论哪个对象发布的与通知名称相同的通知都会被监听的到。

    [notification addObserver:stu selector:@selector(studyNSNotification:) name:@"doWork"object:tea];

     //第六发布通知

     //参数1:通知的名称

     //参数2:通知的发布者

     //参数3:通知的具体内容

    [notification postNotificationName:@"doWork"object:tea userInfo:@{

     @"key_one":@"哈哈",

     @"key_two":@"嘿嘿"

     }

             ];

     //第七移除通知(对象销毁时候移除)

        }

     return0;

    }

    ——————————————— 发布通知的类(Teacher.h)声明文件——————————————— 

    #import <Foundation/Foundation.h>

    @interfaceTeacher : NSObject

    @end

    ——————————————— 发布通知的类(Teacher.m)实现文件——————————————— 

    #import "Teacher.h"

    @implementationTeacher

    @end

    ——————————————— 监听通知的类(Student.h)声明文件——————————————— 

    #import <Foundation/Foundation.h>

    @interfaceStudent : NSObject

    //获取通知的内容

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

    @end

    ——————————————— 监听通知的类(Student.m)实现文件——————————————— 

    #import "Student.h"

    @implementationStudent

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

     //notification.name//通知名;

     //notification.object//发送通知的对象

     //notification.userInfo//发送通知的内容

     NSLog(@"notification = %@",notification);

    }

    -(void)dealloc{

     //对象销毁之前移除通知

        [[NSNotificationCenterdefaultCenter] removeObserver:self];

    }

    @end

    相关文章

      网友评论

          本文标题:第五节:关于通知介绍

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