學習iOS 也有一段時間瞭,通知還沒有看過,今天學習瞭一下;
通知主要是用於不同對象之間的數據共享和線程通信(這些專業的詞組我也不太懂,弄明白什麼事,什麼時候該用就行瞭)。
看瞭無線互聯的關於本地通知的視頻(隻有一個簡單地例子),不過正適合我的胃口。
例子應用場景:
一個child類,在類中有個NSInteger屬性初始化為100,定義一個定時器每兩秒鐘讓這個屬性值減2,當減到90的時候,想通知中心發送一個通知。
一個father類,在類中註冊接收這個通知,當child發送通知的時候father來接收這個通知並作出相應地反映。
@interface Child : NSObject @property (nonatomic,assign) NSInteger num; @end
#import "Child.h" @implementation Child @synthesize num; - (id)init { self = [super init]; if (self) { num = 100; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeobserver:) userInfo:nil repeats:YES]; } return self; } - (void)timeobserver:(NSTimer *)timer { NSLog(@"child:%ld",num); num -= 2; if (num == 90) { [[NSNotificationCenter defaultCenter]postNotificationName:@"child" object:[NSNumber numberWithInteger:num]];//第一個參數為該通知的名字,用於識別通知,第二個參數object為傳遞的參數 } } @end
@implementation Father -(id)init { self = [super init]; if (self) { [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(observer:) name:@"child" object:nil];//註冊接收通知,如果第四個參數為nil表示接收名字為name(第三個參數)的通知,如果第四個參數指定對象,那麼隻接收該對象下名為name的參數。} return self;}- (void)observer:(NSNotification *)notification{ NSInteger i = (NSInteger) notification.object; NSLog(@"%ld",(long)i);}@end