<02> - 通知 <01>

 

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

#import <Foundation/Foundation.h>
#import "Teacher.h"
#import "Student.h"
int main( int argc, const char * argv[]) {
    @autoreleasepool {
     
        //第一 通知的发布者
        Teacher *tea = [[Teacher alloc] init];
        //第二 通知的监听者
        Student *stu = [[Student alloc] init];
        //第四 获取NSNotificationCenter对象
        NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
         //第五 监听通知
        //参数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":@"嘿嘿"
                                                                           }
         ];
       
         //第七 移除通知(对象销毁时候移除
       
       
    }
    return 0;
}
——————————————— 发布通知的类(Teacher.h)声明文件----------------------
 
 
#import <Foundation/Foundation.h>

@interface Teacher : NSObject

@end
 
——————————————— 发布通知的类(Teacher.m)实现文件----------------------
 
#import "Teacher.h"

@implementation Teacher

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

#import <Foundation/Foundation.h>

@interface Student : NSObject
//获取通知的内容
- ( void)studyNSNotification:(NSNotification *)notification;
@end
 
——————————————— 监听通知的类(Student.m)实现文件----------------------
#import "Student.h"
@implementation Student
-( void)studyNSNotification:(NSNotification *)notification{
   
    //notification.name//通知名;
    //notification.object//发送通知的对象
    //notification.userInfo//发送通知的内容
    NSLog( @"notification = %@",notification);
   
}
-( void)dealloc{
   
    //对象销毁之前移除通知
    [[NSNotificationCenter defaultCenter] removeObserver: self];
   
}
@end
 
 

转载于:https://www.cnblogs.com/iQingYang/p/6807967.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值