標籤:
如果學生沒有來上課,老師給家長發送通知
1 #import "Parents.h" 2 // #import "Teacher.h" 3 @implementation Parents 4 5 - (instancetype)init 6 { 7 self = [super init]; 8 if (self) { 9 // 註冊通知10 // addObserver:觀察者,即在什麼地方接收通知,11 // selsctor:受到通知後響應的方法,是一個選取器,用於指定一個接收指定通知的方法12 // name:響應的名字,即通知的名字,只有與通知中樞的通知名相匹配時,才可能接收該通知13 // object:傳遞參數 誰去響應事件 object為nil時除了自己,所有的通知名為isAttenClass的都能接受到通知14 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(attendClass:) name:@"isAttendClass" object:nil];15 }16 return self;17 }18 19 - (void)attendClass:(NSNotification *)notification20 {21 // Teacher *teacher = notification.object;22 NSLog(@"觸發通知");23 NSLog(@"家長你好,%@",[notification userInfo]);24 }25 26 27 28 - (void)dealloc29 {30 // 移除指定通知31 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"isAttendClass" object:nil];32 33 // 移除所有通知34 [[NSNotificationCenter defaultCenter] removeObserver:self];35 }36 37 @end
1 #import <Foundation/Foundation.h> 2 3 #import "Parents.h" 4 5 @interface Teacher : NSObject 6 7 @property (nonatomic,assign) BOOL isAttendClass; 8 9 - (void)postNotification;10 11 @end12 13 14 15 16 17 18 19 20 21 22 #import "Teacher.h"23 24 @implementation Teacher25 26 27 - (void)postNotification28 {29 Parents *parents = [[Parents alloc]init];30 _isAttendClass = NO;31 32 // 發送通知33 // object:發送通知給誰34 if (!_isAttendClass) {35 [[NSNotificationCenter defaultCenter]postNotificationName:@"isAttendClass" object:parents userInfo:@{@"通知":@"孩子沒來上課"}];36 }37 }38 39 @end
object-c之通知