iOS之KVO和KVC

來源:互聯網
上載者:User

標籤:

概述

由於ObjC主要基於Smalltalk進行設計,因此它有很多類似於Ruby、Python的動態特性,例如動態類型、動態載入、動態綁定等。今天我們著重介紹ObjC中的索引值編碼(KVC)、索引值監聽(KVO)特性:

  1. 索引值編碼KVC
  2. 索引值監聽KVO
索引值編碼KVC

我們知道在C#中可以通過反射讀寫一個對象的屬性,有時候這種方式特別方便,因為你可以利用字串的方式去動態控制一個對象。其實由於ObjC的語言特性,你根部不必進行任何操作就可以進行屬性的動態讀寫,這種方式就是Key Value Coding(簡稱KVC)。

KVC的操作方法由NSKeyValueCoding協議提供,而NSObject就實現了這個協議,也就是說ObjC中幾乎所有的對象都支援KVC操作,常用的KVC操作方法如下:

  • 動態設定: setValue:屬性值 forKey:屬性名稱(用於簡單路徑)、setValue:屬性值 forKeyPath:屬性路徑(用於複合路徑,例如Person有一個Account類型的屬性,那麼person.account就是一個複合屬性)
  • 動態讀取: valueForKey:屬性名稱 valueForKeyPath:屬性名稱(用於複合路徑)

下面通過一個例子來理解KVC

Account.h

////  Account.h//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>@interface Account : NSObject#pragma mark - 屬性#pragma mark 餘額@property (nonatomic,assign) float balance;@end

Account.m

////  Account.m//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "Account.h"@implementation Account@end

Person.h

////  Person.h//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>@class Account;@interface Person : NSObject{    @private    int _age;}#pragma mark - 屬性#pragma mark 姓名@property (nonatomic,copy) NSString *name;#pragma mark 賬戶@property (nonatomic,retain) Account *account;#pragma mark - 公用方法#pragma mark 顯示人員資訊-(void)showMessage;@end

Person.m

////  Person.m//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "Person.h"@implementation Person#pragma mark - 公用方法#pragma mark 顯示人員資訊-(void)showMessage{    NSLog(@"name=%@,age=%d",_name,_age);}@end

main.m

////  main.m//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>#import "Person.h"#import "Account.h"int main(int argc, const char * argv[]) {    @autoreleasepool {                Person *person1=[[Person alloc]init];        [person1 setValue:@"Kenshin" forKey:@"name"];        [person1 setValue:@28 forKey:@"age"];//注意即使一個私人變數仍然可以訪問                [person1 showMessage];        //結果:name=Kenshin,age=28        NSLog(@"person1‘s name is :%@,age is :%@",person1.name,[person1 valueForKey:@"age"]);        //結果:person1‘s name is :Kenshin,age is :28                                        Account *account1=[[Account alloc]init];        person1.account=account1;//注意這一步一定要先給account屬性賦值,否則下面按路徑賦值無法成功,因為account為nil,當然這一步驟也可以寫成:[person1 setValue:account1 forKeyPath:@"account"];                [person1 setValue:@100000000.0 forKeyPath:@"account.balance"];                NSLog(@"person1‘s balance is :%.2f",[[person1 valueForKeyPath:@"account.balance"] floatValue]);        //結果:person1‘s balance is :100000000.00                                    }    return 0;}

KVC使用起來比較簡單,但是它如何尋找一個屬性進行讀取呢?具體尋找規則(假設現在要利用KVC對a進行讀取):

  • 如果是動態設定屬性,則優先考慮調用setA方法,如果沒有該方法則優先考慮搜尋成員變數_a,如果仍然不存在則搜尋成員變數a,如果最後仍然沒 搜尋到則會調用這個類的setValue:forUndefinedKey:方法(注意搜尋過程中不管這些方法、成員變數是私人的還是公用的都能正確設 置);
  • 如果是動態讀取屬性,則優先考慮調用a方法(屬性a的getter方法),如果沒有搜尋到則會優先搜尋成員變數_a,如果仍然不存在則 搜尋成員變數a,如果最後仍然沒搜尋到則會調用這個類的valueforUndefinedKey:方法(注意搜尋過程中不管這些方法、成員變數是私人的 還是公用的都能正確讀取);
索引值監聽KVO

我們知道在WPF、Silverlight中都有一種雙向繫結機制,如果資料模型修改了之後會立即反映到UI視圖上,類似的還有如今比較流行的基於 MVVM設計模式的前端架構,例如Knockout.js。其實在ObjC中原生就支援這種機制,它叫做Key Value Observing(簡稱KVO)。KVO其實是一種觀察者模式,利用它可以很容易實現視圖組件和資料模型的分離,當資料模型的屬性值改變之後作為監聽器 的視圖組件就會被激發,激發時就會回調監聽器自身。在ObjC中要實現KVO則必須實現NSKeyValueObServing協議,不過幸運的是 NSObject已經實現了該協議,因此幾乎所有的ObjC對象都可以使用KVO。

在ObjC中使用KVO操作常用的方法如下:

  • 註冊指定Key路徑的監聽器: addObserver: forKeyPath: options:  context:
  • 刪除指定Key路徑的監聽器: removeObserver: forKeyPathremoveObserver: forKeyPath: context:
  • 回調監聽: observeValueForKeyPath: ofObject: change: context:

KVO的使用步驟也比較簡單:

  1. 通過addObserver: forKeyPath: options: context:為被監聽對象(它通常是資料模型)註冊監聽器
  2. 重寫監聽器的observeValueForKeyPath: ofObject: change: context:方法

由於我們還沒有介紹過IOS的介面編程,這裡我們還是在上面的例子基礎上繼續擴充,假設當我們的賬戶餘額balance變動之後我們希望使用者可以及 時獲得通知。那麼此時Account就作為我們的被監聽對象,需要Person為它註冊監聽(使用addObserver: forKeyPath: options: context:);而人員Person作為監聽器需要重寫它的observeValueForKeyPath: ofObject: change: context:方法,當監聽的餘額發生改變後會回調監聽器Person監聽方法(observeValueForKeyPath: ofObject: change: context:)。下面通過代碼類比上面的過程:

Account.h

////  Account.h//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>@interface Account : NSObject#pragma mark - 屬性#pragma mark 餘額@property (nonatomic,assign) float balance;@end

Account.m

////  Account.m//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "Account.h"@implementation Account@end

Person.h

////  Person.h//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>@class Account;@interface Person : NSObject{    @private    int _age;}#pragma mark - 屬性#pragma mark 姓名@property (nonatomic,copy) NSString *name;#pragma mark 賬戶@property (nonatomic,retain) Account *account;#pragma mark - 公用方法#pragma mark 顯示人員資訊-(void)showMessage;@end

Person.m

////  Person.m//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import "Person.h"#import "Account.h"@implementation Person#pragma mark - 公用方法#pragma mark 顯示人員資訊-(void)showMessage{    NSLog(@"name=%@,age=%d",_name,_age);}#pragma mark 設定人員賬戶-(void)setAccount:(Account *)account{    _account=account;    //添加對Account的監聽    [self.account addObserver:self forKeyPath:@"balance" options:NSKeyValueObservingOptionNew context:nil];}#pragma mark - 覆蓋方法#pragma mark 重寫observeValueForKeyPath方法,當賬戶餘額變化後此處獲得通知-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    if([keyPath isEqualToString:@"balance"]){//這裡只處理balance屬性        NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);    }}#pragma mark 重寫銷毀方法-(void)dealloc{    [self.account removeObserver:self forKeyPath:@"balance"];//移除監聽    //[super dealloc];//注意啟用了ARC,此處不需要調用}@end

main.m

////  main.m//  KVCAndKVO////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h>#import "Person.h"#import "Account.h"int main(int argc, const char * argv[]) {    @autoreleasepool {                Person *person1=[[Person alloc]init];        [email protected]"Kenshin";        Account *account1=[[Account alloc]init];        account1.balance=100000000.0;        person1.account=account1;                account1.balance=200000000.0;//注意執行到這一步會觸發監聽器回呼函數observeValueForKeyPath: ofObject: change: context:        //結果:keyPath=balance,object=<Account: 0x100103aa0>,newValue=200000000.00,context=(null)                    }    return 0;}

在上面的代碼中我們在給人員分配賬戶時給賬戶的balance屬性添加了監聽,並且在監聽回調方法中輸出了監聽到的資訊,同時在對象銷毀時移除監聽,這就構成了一個典型的KVO應用。

iOS之KVO和KVC

聯繫我們

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