IOS-KVC/KVO

來源:互聯網
上載者:User

IOS-KVC/KVO

KVC 簡介設值的一個工具,對於指向id的對象,像其記憶體存取值。這有點像java的反射;

存在如下一個對象,已知其屬性name,可取值: 

id p=[[Person alloc] init];NSString *name=[p valueForKey:@"name"];

假設,有一個數組,裡面存在一系列的對象,我們想取出某一屬性放在一個隊列中,如下:

Book *book1=[[Book alloc] init];        book1.name=@"effctive c++";                Book *book2=[[Book alloc] init];        book2.name=@" more effctive c++";                Book *book3=[[Book alloc] init];        book3.name=@" most effctive c++";                NSArray *arr=@[book1,book2,book3];                NSLog(@"%@",[arr valueForKey:@"name"]);

生活中,我們確實存在以上的需求;


KVO指的是設值過程中對其監聽的過程,以實現對商務邏輯的校正

//建立一個被監視的對象        Book *book1=[[Book alloc] init];                //設定監聽對象        BookObserve *observe=[[BookObserve alloc] init];                //對其存值的監聽-這種方法用完後不需要移除監聽器        [observe observeValueForKeyPath:@"name" ofObject:book1 change:nil context:@"sadsada"];                //對其存值的監聽-02        [book1 addObserver:observe forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];                book1.name=@" most effctive c++";        NSLog(@"%@",book1.name);                //取消對其存值的監聽-02        [book1 removeObserver:observe forKeyPath:@"name"];

對於監聽對象,無需實現任何代理,因為他是NSObject的衍生類別

只要在.m檔案中實現如下方法即可監聽:

#pragma mark keyPath:對象屬性 object:對象 change:存取值儲存的字典-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{}




聯繫我們

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