標籤:
NSNotification即通知,可以實現一個對象發送通知,多個對象接收到通知。
工作流程:
在需要發送通知的類中添加一個通知中樞(單例)。
在需要發送通知的類中發送通知,發送通知的對象是self,可定義相應的使用者資訊,通知名可以是任意定義的字串,監聽通知需要和此通知名匹配。
在需要接收通知的類中添加通知的接收對象,用來監聽發出的通知,下面自訂一個接收者的相應方法,方法名封裝到上面的接收對象。
最後移除當前對象監聽的通知。
舉例:在孩子這個類中發送通知,告知孩子髒了,在保姆這個類中接收通知,並實現給孩子洗澡這個方法。
#import "Child.h"@implementation Child- (instancetype)init { if (self = [super init]) { _cleanValue = 100; _happyValue = 100; } [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES]; return self;}- (void)timerAction:(NSTimer *)timer { _cleanValue--; _happyValue--; NSLog(@"cleanValue:%li, happyValue:%li", _cleanValue, _happyValue); if (_cleanValue == 95) { //擷取到通知中樞對象----單例,在記憶體中只有一個通知中樞對象 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; //發送通知,帶使用者資訊的通知 //使用者資訊可由可無,後面被列印出來了 NSDictionary *userInfo = @{ @"name" : @"tengteng", @"age" : @"22" }; [center postNotificationName:@"BathNotification" object:self userInfo:userInfo]; } }@end
#import "Nanny.h"#import "Child.h"@implementation Nanny//接受到通知後針對此事件要作出響應- (instancetype)init { if (self = [super init]) { //監聽通知 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(cleanValueAction:) name:@"BathNotification" object:nil]; } return self;}- (void)cleanValueAction:(NSNotification *)notification { //保姆對小孩髒了這個事件的響應 NSLog(@"保姆給小孩洗澡"); //擷取到通知的寄件者,即小孩,這樣才能更改小孩的潔淨程度的屬性 Child *child = (Child *)notification.object; //可以通過notification來擷取到通知寄件者傳遞的資訊 NSLog(@"userInfo:%@", notification.userInfo); child.cleanValue = 100;}- (void)dealloc { //移除當前對象對所有通知的監聽 [[NSNotificationCenter defaultCenter] removeObserver:self];}@end
iOS開發————通訊方式之NSNotification