我們先來看看在蘋果的Cocoa Touch框架中有誰使用了觀察者模式:
1.通知(notification)機制
在通知機制中對某個通知感興趣的所有對象都可以成為接受者。首先,這些對象需要向通知中心(NSNotificationCenter)發出addObserver:selector:name:object:消息進行注冊,在投送對象投送通知送給通知中心時,通知中心就會把通知廣播給注冊過的接受者。所有的接受者不知道通知是誰投送的,不去關心它的細節。投送對象和接受者是一對多的關系。接受者如果對通知不再關注,會給通知中心發送removeObserver:name:Object:消息解除注冊,以后不再接受通知。
(ps:這段話內容摘抄自關東升先生的文章)
我們試著去使用一下通知機制:
新建一個Single view Project,對項目中的文件做以下修改:
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[NSNotificationCenter defaultCenter]postNotificationName:@"APPTerminate" object:self];
}
ViewController.m
//
//? ViewController.m
//? TestNotification
//
//? Created by liwenqian on 14-10-18.
//? Copyright (c) 2014年 liwenqian. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//注意此處的selector有參數,要加冒號
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomething:) name:@"APPTerminate" object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[[NSNotificationCenter defaultCenter]removeObserver:self];
// Dispose of any resources that can be recreated.
}
#pragma mark -處理通知
-(void)doSomething:(NSNotification*)notification{
NSLog(@"收到通知");
}
@end
如上所示,對模版項目的兩個文件的方法或整個文件做出修改,Command+R運行你的APP,再按下Home鍵(Command+H),會發現打印出一行收到通知的文字,如下:
? 收到通知
2.KVO(Key-Value-Observing)機制
? 原理圖如下:
如圖所示:
該機制下觀察者的注冊是在被觀察者的內部進行的,不同于通知機制(由觀察者自己注冊),需要被觀察者和觀察者同時實現一個協議:NSKeyValueObserving,被觀察者通過addObserver:forKeypath:options:context方法注冊觀察者,以及要被觀察的屬性。