题目-通知-NSNoticafiction
Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject @property(nonatomic,copy)NSString*name; @property(nonatomic,assign)long int ID; -(void)addObserver;//添加观察者 -(void)postNotification;//发通知 -(void)saySomething; -(instancetype)initWithName:(NSString*)name andID:(long int)ID; @end
Person.m
#import "Person.h" @implementation Person - (instancetype)initWithName:(NSString *)name andID:(long)ID { self = [super init]; if (self) { _name=name; _ID=ID; } return self; } //添加观察者 /* 第一个参数:观察者 第二个参数:回调方法 第三个参数:通知的唯一标识 第四个参数:发布者 */ -(void)addObserver{ [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gotoMeeting:) name:@"MEETING" object:nil]; } //实现回调函数 -(void)gotoMeeting:(NSNotification*)notification{ NSLog(@"%@",notification.userInfo); //notification.userInfo=@{@"date":@"8-20",@"classMeeting":@"kaoshi"} [self saySomething]; } -(void)saySomething{} //发通知 -(void)postNotification{ [[NSNotificationCenter defaultCenter]postNotificationName:@"MEETING" object:nil userInfo:@{@"date":@"8-20",@"class Meeting":@"kaoshi"}]; } @end
Teacher.h
#import "Person.h" @interface Teacher : Person @property(nonatomic,copy)NSString*subject; -(instancetype)initWithName:(NSString *)name andID:(long)ID andSubject:(NSString*)subject; @end
Teacher.m
#import "Teacher.h" @implementation Teacher - (instancetype)initWithName:(NSString *)name andID:(long)ID andSubject:(NSString *)subject { self = [super init]; self=[super initWithName:name andID:ID]; if (self) { _subject=subject; } return self; } @end
Student.h
#import "Person.h" @interface Student : Person @end
Student.m
#import "Student.h" @implementation Student //4.移除观察者(监听者) -(void)dealloc{ [[NSNotificationCenter defaultCenter]removeObserver:self]; } -(void)saySomething{ NSLog(@"完了"); } @end
Parent.h
#import "Person.h" @interface Parent : Person @end
Parent.m
#import "Parent.h" @implementation Parent //4.移除观察者(监听者) -(void)dealloc{ [[NSNotificationCenter defaultCenter]removeObserver:self]; } -(void)saySomething{ NSLog(@"加油"); } @end
main.m
#import <Foundation/Foundation.h> #import "Teacher.h" #import "Student.h" #import "Parent.h" #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Teacher*teacher=[[Teacher alloc]initWithName:@"王老师" andID:@"1101" andSubject:@"ios"]; Student*student=[[Student alloc]initWithName:@"李明" andID:@"1201"]; Parent*parent=[[Parent alloc]initWithName:@"李明博" andID:@"1301"]; [student addObserver]; [parent addObserver]; [teacher postNotification]; } return 0; }
输出结果
2015-08-18 17:30:04.971 NSNoticafiction[2825:103009] {
"class Meeting" = kaoshi;
date = "8-20";
}
2015-08-18 17:30:04.972 NSNoticafiction[2825:103009] 完了
2015-08-18 17:30:04.972 NSNoticafiction[2825:103009] {
"class Meeting" = kaoshi;
date = "8-20";
}
2015-08-18 17:30:04.972 NSNoticafiction[2825:103009] 加油