iOS.OC.02 KVC-索引值編碼,ios.oc.02kvc-索引值
KVC 是key,value,coding的縮寫,即索引值編碼。在iOS中,可以通過類的屬性的名稱(key),來間接訪問對象的屬性資訊。
建一個工程,建立一個Person類,它有兩個屬性,name和age。
Person.h:
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString * name,age;
}
@end
ViewController.h:
在ViewController.h檔案中引入Person類標頭檔,ViewController有一個Person類型的屬性jay。
#import <UIKit/UIKit.h>
#import "Person.h"
@interface ViewController : UIViewController
@property(nonatomic,retain)Person * jay;
@end
ViewController.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//建立Person對象jay
_jay=[[Person alloc]init];
//通過key,value設定對象jay的資訊
[_jay setValue:@"糾結倫" forKey:@"name"];
[_jay setValue:@"30" forKey:@"age"];
//通過Person的屬性訪問jay這個對象的資訊。
NSLog(@"%@",[_jay valueForKey:@"name"]);
NSLog(@"%@",[_jay valueForKey:@"age"]);
}
列印結果:
2015-03-21 15:31:27.536 OMG[1677:116165] 糾結倫
2015-03-21 15:31:27.537 OMG[1677:116165] 30
一個類(Person)的對象(jay)通過setValue:forKey語句,來設定對象屬性的資訊,其中Key就是類(person)的屬性,也是該對象(jay)的屬相,這裡的key分別是name和age,通過key設定它們的資訊。再通過對象調用valueforkey:語句可以訪問到key對應的屬性資訊。