KVC就是 key--value—coding 可以在沒有給屬性設置property的情況下訪問屬性。
編寫了一個接口 定義了一個有複合屬性和基本屬性:
#import <Cocoa/Cocoa.h>
#import "Author.h"
@interface Books : NSObject {
NSString * name;
Author * author;
float price;
NSArray * array;
}
@end
下面是Author接口:
#import <Cocoa/Cocoa.h>
@interface Author : NSObject {
NSString * name;
}
@end
下面是主函數中的內容 ,練習一下KVC是怎樣實現的
NSAutoreleasePool * pool =[[NSAutoreleasePool alloc]init];
Books * book=[[[Books alloc]init]autorelease];
Author * author=[[[Author alloc]init]autorelease];
[book setValue:@"Ojbect-C 入門" forKey:@"name"];
[author setValue:@"hongxing" forKey:@"name"];
[book setValue:author forKey:@"author"];
NSLog(@"this is authorname:%@",[author valueForKey:@"name"]);
NSLog(@"this is bookname:%@",[book valueForKey:@"name"]);
NSLog(@"this is book.author.name:%@",[book valueForKeyPath:@"author.name"]);
Books * book1=[[[Books alloc]init]autorelease];
[book1 setValue:@"4.5" forKey:@"price"];
[book1 setValue:author forKey:@"author"];
Books * book2=[[[Books alloc]init]autorelease];
[book2 setValue:@"5.4" forKey: @"price"];
NSArray *array=[NSArray arrayWithObjects:book1,book2,nil];
[book setValue:array forKey:@"array"];
NSLog(@"books price is:%@",[book valueForKeyPath:@"array.price"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"[email protected]"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"[email protected]"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"[email protected]"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"[email protected]"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"[email protected]"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"array.author.name"]);
[pool drain];