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