iOS常用設計模式——觀察者設計模式

來源:互聯網
上載者:User

iOS常用設計模式——觀察者設計模式
觀察者設計模式詳解

觀察者設計模式詳解 基本概念 NSNotificationCenter的使用 添加監聽 接收訊息 刪除監視 KVO的使用 基本概念 註冊觀察者 觀察者對象發生變化時的回調方法 remove觀察者身份 代碼實現

基本概念

觀察者模式定義了一種一對多的依賴關係,讓多個觀察者對象同時監聽某一個主題對象。這個主題對象在狀態發生變化時,會通知所有觀察者對象,使它們能夠自動更新自己.而在IOS開發中我們可能會接觸到的經典觀察者模式的實現方式,有這麼幾種:NSNotificationCenter、KVO、Delegate等

NSNotificationCenter的使用添加監聽(void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
sample:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:GET_UP object:nil];
說明:
【NSNotificationCenter defaultCenter】訊息中心只有一個,通過該方法擷取該類的單例
addObserver:添加監聽者
selector:表示監聽到到對象後的處理函數
name:表示註冊所關心的訊息名稱接收訊息(void)postNotification:(NSNotification *)notification; (void)postNotificationName:(NSString *)aName object:(id)anObject; (void)postNotificationName:(NSString )aName object:(id)anObject userInfo:(NSDictionary )aUserInfo;
sample:
[[NSNotificationCenter defaultCenter] postNotificationName:GET_UP object:[NSNumber numberWithInteger:self.time]];
分析:
GET_UP:推送訊息的名稱
object:發送訊息的對象
userInfo:發送訊息攜帶的資訊刪除監視(void)removeObserver:(id)observer; (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;KVO的使用基本概念

KVO,即:Key-Value Observing,它提供一種機制,當指定的對象的屬性被修改後,則對象就會接受到通知。該方法與NSNotification有很大的不同,它並不需要一個NotificationCenter來為所有觀察者提供變化通知,相反的是,當有變化發生時,該通知直接發送給觀察者,NSObject為我們實現了此方法。
利用此方法我們可以觀察對象,是一種一對多的關係。

註冊觀察者

首先必鬚髮送一個
addObserver:selfforKeyPath:@”happyNum” options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld
context:nil]訊息至觀察對象,用以傳送觀察對象和需要觀察的屬性的關鍵路徑,參數分析:
- (void)addObserver:(NSObject )observer forKeyPath:(NSString )keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
observer:表示觀察者是誰,一般為self
keyPath: 表示觀察哪個對象
options:NSKeyValueObservingOptionNew表示觀察新值,NSKeyValueObservingOptionOld表示觀察舊值
context:表示上下文環境

觀察者對象發生變化時的回調方法

(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {

NSLog(@”%@”,change);
}
參數分析:
change:表示發生改變時返回的值
keyPath:表示觀察對象
contenst:表示上下文

remove觀察者身份

發送一條制定觀察方對象和路徑來移除觀察者,該函數一般放在dealloc:
[self.childremoveObserver:selfforKeyPath:@”happyNum”context:nil];

代碼實現
child.h#import @interface Child : NSObject@property(nonatomic,assign)NSInteger happyNum;@endchild.m#import "Child.h"@implementation Child-(id)init{    self=[super init];    if(self)    {        self.happyNum=100;        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(decrease:) userInfo:nil repeats:YES];    }    return  self;}-(void)decrease:(NSTimer*)timer{  // NSLog(@"the happyNum is %ld",self.happyNum);    _happyNum--;   // [self setValue:[NSNumber numberWithInteger:_happyNum] forKey:@"happyNum"];}@endnurse.h#import #import "Child.h"@interface Nurse : NSObject@property(nonatomic,retain)Child *child;-(id)initWithChild:(Child*)child;@endnurse.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];}@endmain.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];        //[nurseObj release];    }    return 0;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.