iOS.OC.03 KVO-索引值觀察者,ios.oc.03kvo-

來源:互聯網
上載者:User

iOS.OC.03 KVO-索引值觀察者,ios.oc.03kvo-

KVO Key,Value,Observing,即索引值觀察者。它提供了這樣一種機制,當指定對象的屬性發生改變時,KVO會自動通知相應的觀察者。

它與NSNotification不同,鍵-值觀察中並沒有所謂的中心對象來為所有觀察者 提供變化通知。取而代之地,當有變化發生時,通知被直接發送至處於觀察狀態的對象。

三個步驟:註冊觀察者,接收變更通知,移除觀察者。執行個體如下:

建立一個工程,建立兩個類,一個Baby,一個Mother。Baby有一個屬性hungryNum,叫饑餓值吧,當饑餓值改變的時候mother接收饑餓值變更。

Baby.h

#import <Foundation/Foundation.h>

@interface Baby : NSObject

@property(nonatomic,assign)NSInteger hungryNum;

@end

 

Mother.m

#import "Mother.h"

 @implementation Mother

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

     if ([keyPath isEqualToString:@"hungryNum"]) {

       //每當監聽的屬性hungryNum改變時,列印hungryNum的當前值和之前值。

       NSLog(@"%@  %@",[change objectForKey:@"new"],[change objectForKey:@"old"]);

  }

}

 @end

 

ViewController.m

#import "ViewController.h"

#import "Baby.h"//引入標頭檔

#import "Mother.h"

@interface ViewController ()

@end

 @implementation ViewController

 - (void)viewDidLoad {

    [super viewDidLoad];

    Baby * xiaoxiao=[[Baby alloc]init];//建立對象

    Mother * xiaoMama=[[Mother alloc]init];

    

  //註冊觀察者,xiaoxiao添加了觀察者xiaoxiaoMama,觀察hungryNum屬性。

     [xiaoxiao addObserver:xiaoMama forKeyPath:@"hungryNum" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

    xiaoxiao.hungryNum=10;//給xiaoxiao的hungryNum屬性附一個初值,用一個for迴圈使得該屬性的值改變,每次值改變都會通知監聽者。

    for (xiaoxiao.hungryNum; xiaoxiao.hungryNum>0; xiaoxiao.hungryNum--) {

    }

    //移除觀察者,注意:如果不移除,程式運行到此會奔潰。

    [xiaoxiao removeObserver:xiaoMama forKeyPath:@"hungryNum"];

}

 

列印結果:

2015-03-21 17:11:29.735 OMG[2366:148640] 10  0

2015-03-21 17:11:29.736 OMG[2366:148640] 9  10

2015-03-21 17:11:29.736 OMG[2366:148640] 8  9

2015-03-21 17:11:29.736 OMG[2366:148640] 7  8

2015-03-21 17:11:29.736 OMG[2366:148640] 6  7

2015-03-21 17:11:29.736 OMG[2366:148640] 5  6

2015-03-21 17:11:29.736 OMG[2366:148640] 4  5

2015-03-21 17:11:29.737 OMG[2366:148640] 3  4

2015-03-21 17:11:29.737 OMG[2366:148640] 2  3

2015-03-21 17:11:29.737 OMG[2366:148640] 1  2

2015-03-21 17:11:29.737 OMG[2366:148640] 0  1

 

如有錯誤,請不吝賜教,必改之。

相關文章

聯繫我們

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