觀察者模式定義了一對多的依賴關係:多個觀察者同時關注同一個主題物件,當主題的狀態改變時,所有觀察者會自動收到通知並更新自己。在 iOS 開發中,最常見的實作方式有 NSNotificationCenter、KVO 與 Delegate 三種,本文聚焦前兩者。
通知中心是全域廣播式的機制,發送方與接收方之間不需要持有彼此的參考,因此耦合度最低。
- (void)addObserver:(id)observer
selector:(SEL)aSelector
name:(NSString *)aName
object:(id)anObject;
範例:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doSomething:)
name:GET_UP
object:nil];
參數說明:
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSString *)aName object:(id)anObject;
- (void)postNotificationName:(NSString *)aName
object:(id)anObject
userInfo:(NSDictionary *)aUserInfo;
範例:
[[NSNotificationCenter defaultCenter] postNotificationName:GET_UP
object:[NSNumber numberWithInteger:self.time]];
userInfo 是通知攜帶的附加資料,接收端可以從中取出需要的內容。
- (void)removeObserver:(id)observer; - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
建議在 dealloc 中移除,否則觀察者釋放後若仍收到通知,會造成 crash。
KVO 提供的是另一種機制:當指定物件的屬性被修改時,物件會直接收到通知。它不需要通知中心居中轉發,而是把變化直接送給觀察者,底層由 NSObject 為我們實作。這同樣是一種一對多的關係。
- (void)addObserver:(NSObject *)observer
forKeyPath:(NSString *)keyPath
options:(NSKeyValueObservingOptions)options
context:(void *)context;
範例:
[self.child addObserver:self
forKeyPath:@"happyNum"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
參數說明:keyPath 指定要觀察的屬性名稱;options 中 New 代表取得新值、Old 代表取得舊值;context 用於在回呼時辨識是哪一次註冊。
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
NSLog(@"%@", change);
}
[self.child removeObserver:self forKeyPath:@"happyNum" context:nil];
同樣建議放在 dealloc 中,否則會出現無 observer 可移除的執行期錯誤。
// Child.h #import@interface Child : NSObject @property (nonatomic, assign) NSInteger happyNum; @end // Child.m #import "Child.h" @implementation Child - (id)init { self = [super init]; if (self) { self.happyNum = 100; // 每秒讓 happyNum 遞減,模擬狀態變化 [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(decrease:) userInfo:nil repeats:YES]; } return self; } - (void)decrease:(NSTimer *)timer { _happyNum--; } @end // Nurse.h #import #import "Child.h" @interface Nurse : NSObject @property (nonatomic, retain) Child *child; - (id)initWithChild:(Child *)child; @end // Nurse.m #import "Nurse.h" @implementation Nurse - (id)initWithChild:(Child *)child { self = [super init]; if (self) { self.child = child; [self.child addObserver:self forKeyPath:@"happyNum" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; } return self; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"%@", change); } - (void)dealloc { [self.child removeObserver:self forKeyPath:@"happyNum" context:nil]; [_child release]; [super dealloc]; } @end // main.m #import #import "Child.h" #import "Nurse.h" int main(int argc, const char *argv[]) { @autoreleasepool { Child *childObj = [[[Child alloc] init] autorelease]; Nurse *nurseObj = [[[Nurse alloc] initWithChild:childObj] autorelease]; [[NSRunLoop currentRunLoop] run]; } return 0; }
NSNotificationCenter 適合跨層級、跨模組的寬鬆事件廣播,例如「使用者登入成功」、「購物車內容變更」,發送方不需要知道誰在聽。KVO 適合直接觀察某個物件的特定屬性變化,寫法直觀但要注意移除時機。Delegate 則是三者中耦合最緊、型別最明確的一種,適合一對一且雙方關係固定的場景。