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:@"array.@count.price"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"array.@avg.price"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"array.@max.price"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"array.@min.price"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"array.@sum.price"]);
NSLog(@"books price count is:%@",[book valueForKeyPath:@"array.author.name"]);
[pool drain];