———————————————? main.m文件———————————————?
#import?
#import?"Teacher.h"
#import?"Student.h"
intmain(intargc,?constchar* argv[]) {
?@autoreleasepool{
?//第一通知的發(fā)布者
?Teacher*tea = [[Teacheralloc]?init];
?//第二通知的監(jiān)聽者
?Student*stu = [[Studentalloc]?init];
?//第四獲取NSNotificationCenter對象
?NSNotificationCenter*notification = [NSNotificationCenterdefaultCenter];
?//第五監(jiān)聽通知
?//參數(shù)1:要監(jiān)聽的對象
?//參數(shù)2:該對象的哪個(gè)方法用來監(jiān)聽這個(gè)通知
?//參數(shù)3:被監(jiān)聽通知的名稱
?//參數(shù)4:發(fā)布通知的對象
?//1》如果沒有指定參數(shù)3(即參數(shù)三為nil)拌蜘,但指定定了參數(shù)4為tea你踩,那么凡事tea對戲那個(gè)發(fā)布的所有通知tea都會(huì)監(jiān)聽到凰荚。
?//2》如果指定了參數(shù)3,但沒指定參數(shù)4邪码,那么無論哪個(gè)對象發(fā)布的與通知名稱相同的通知都會(huì)被監(jiān)聽的到浅萧。
[notification?addObserver:stu?selector:@selector(studyNSNotification:)?name:@"doWork"object:tea];
?//第六發(fā)布通知
?//參數(shù)1:通知的名稱
?//參數(shù)2:通知的發(fā)布者
?//參數(shù)3:通知的具體內(nèi)容
[notification?postNotificationName:@"doWork"object:tea?userInfo:@{
?@"key_one":@"哈哈",
?@"key_two":@"嘿嘿"
?}
???????? ];
?//第七移除通知(對象銷毀時(shí)候移除)
?? ?}
?return0;
}
———————————————?發(fā)布通知的類(Teacher.h)聲明文件———————————————?
#import <Foundation/Foundation.h>
@interfaceTeacher :?NSObject
@end
———————————————?發(fā)布通知的類(Teacher.m)實(shí)現(xiàn)文件———————————————?
#import?"Teacher.h"
@implementationTeacher
@end
———————————————?監(jiān)聽通知的類(Student.h)聲明文件———————————————?
#import <Foundation/Foundation.h>
@interfaceStudent :?NSObject
//獲取通知的內(nèi)容
- (void)studyNSNotification:(NSNotification*)notification;
@end
———————————————?監(jiān)聽通知的類(Student.m)實(shí)現(xiàn)文件———————————————?
#import?"Student.h"
@implementationStudent
-(void)studyNSNotification:(NSNotification*)notification{
?//notification.name//通知名;
?//notification.object//發(fā)送通知的對象
?//notification.userInfo//發(fā)送通知的內(nèi)容
?NSLog(@"notification = %@",notification);
}
-(void)dealloc{
?//對象銷毀之前移除通知
??? [[NSNotificationCenterdefaultCenter]?removeObserver:self];
}
@end