iOS-觀察者模式

來源:互聯網
上載者:User

標籤:

cocoa架構中很多地方都使用了觀察者模式

一、KVO

Key-Value Observing,它提供一種機制,當指定的對象的屬性被修改後,則對象就會接受到通知。每次指定的被觀察的對象的屬性被修改後,KVO自動通知相應的觀察者。

model中的定義:

@interface StockData : NSObject {    NSString * stockName;    float price;}@end@implementation StockData@end

controller中使用,記得上一篇怎麼說的嗎?這裡相當於跟模型說,我要收聽你的更新廣播

- (void)viewDidLoad{    [super viewDidLoad];    stockForKVO = [[StockData alloc] init];    [stockForKVO setValue:@"searph" forKey:@"stockName"];    [stockForKVO setValue:@"10.0" forKey:@"price"];        [stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];    myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];    myLabel.textColor = [UIColor redColor];    myLabel.text = [stockForKVO valueForKey:@"price"];    [self.view addSubview:myLabel];       UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];    b.frame = CGRectMake(0, 0, 100, 30);    [b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:b];}

使用者單擊View中的button調用控制器中的action去更改模型中的資料

-(void) buttonAction{    [stockForKVO setValue:@"20.0" forKey:@"price"];}

控制器需要實現的回調,相當於收到廣播後我應該做啥事

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    if([keyPath isEqualToString:@"price"])    {        myLabel.text = [stockForKVO valueForKey:@"price"];    }}

視圖dealloc需要取消觀察

- (void)dealloc{    [super dealloc];    [stockForKVO removeObserver:self forKeyPath:@"price"];    [stockForKVO release];}
二、Notification

通知使用起來非常的簡單:

首先定義回調,即發生通知了我應該做啥事。

- (void)callBack{    NSLog(@"我收到通知了!");}

其次,註冊通知,即告訴通知中樞,我對啥通知感興趣

[[NSNotificationCenter defaultCenter] addObserver: self    selector: @selector(callBack)    name: @"A類通知"    object: nil];

第三,在程式任何一個地方都可以發送通知

- (void)getNotofocation{    NSLog(@"get it.");    //發出通知    [[NSNotificationCenter defaultCenter] postNotificationName:@"A類通知" object:self];}

當然,也可以在需要的時候取消註冊通知。

iOS-觀察者模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.