IOS開發之KVC與KVO簡述,ioskvckvo

來源:互聯網
上載者:User

IOS開發之KVC與KVO簡述,ioskvckvo

KVC:Key-Value Coding

KVO:Key-Value Observing

 

Person.m

@interface Person : NSObject{    //該存取修飾詞用於說明即使私人成員變數也可以通過kvc方式訪問和賦值    @private    NSString *_name;}@end@implementation Person@end

PersonObserve.m

@interface PersonObserve : NSObject@end@implementation PersonObserve- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    Person *p = (Person *)object;    //使用kvc方式擷取成員變數keypath的值    NSLog(@"%@",[p valueForKey:keyPath]);}@end

main.m

int main(int argc, const char * argv[]) {    //觀察者類    PersonObserve *po = [[PersonObserve alloc] init];    Person *p = [[Person alloc] init];    //使用kvo方式對成員變數“name”的屬性值變化增加觀察者po    //po將在該屬性值發生變化時執行- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context方法    [p addObserver:po forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];        //通過kvc方式設定成員變數“name”的屬性值    //出發觀察者執行對應方法    [p setValue:@"yangys" forKey:@"name"];        //移除對私人成員變數“name”的觀察    [p removeObserver:po forKeyPath:@"name"];    return 0;}

結果:

2015-03-02 20:57:52.487 KVC&KOC[843:24874] yangysProgram ended with exit code: 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.