iOS.OC.02 KVC-索引值編碼,ios.oc.02kvc-索引值

來源:互聯網
上載者:User

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對應的屬性資訊。

相關文章

聯繫我們

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