新建工程如下:
新建一个读者类:
编辑Author.h如下:
// // Author.h // KVC的基本用法 // // Created by apple on 15/9/20. // Copyright (c) 2015年 LiuXun. All rights reserved. // #import <Foundation/Foundation.h> // 作者类——>书籍1、书籍2、书籍3 @interface Author : NSObject { @private NSString *_name; // 作者姓名 // 作者出版的书 NSArray *_issueBook; } @end
新建book类
编辑Book.h如下:
// // Book.h // KVC的基本用法 // // Created by apple on 15/9/20. // Copyright (c) 2015年 LiuXun. All rights reserved. // #import <Foundation/Foundation.h> #import "Author.h" // 书籍类 @interface Book : NSObject { @private Author *_author; // 书的作者 } @property (nonatomic, strong) NSString *name; @property (nonatomic, assign) float price; @end
// // main.m // KVC的基本用法 // // Created by apple on 15/9/20. // Copyright (c) 2015年 LiuXun. All rights reserved. // #import <Foundation/Foundation.h> #import "Book.h" #import "Author.h" int main(int argc, const char * argv[]) { @autoreleasepool { Book *book = [[Book alloc] init]; Author *author = [[Author alloc] init]; [book setValue:author forKey:@"author"]; // 通过键值路径设置属性值 [book setValue:@"莫言" forKeyPath:@"author.name"]; NSString *name = [author valueForKey:@"name"]; NSLog(@"name= %@",name); // 通过键值路径,访问属性值 NSString *nam = [book valueForKeyPath:@"author.name"]; NSLog(@"nam = %@",nam); /*---------------------根据KVC一对多关系进行运算--------------------------*/ Author *author2 = [[Author alloc] init]; [author2 setValue:@"莫言" forKey:@"name"]; Book *book1 = [[Book alloc] init]; book1.name = @"红高粱"; book1.price = 9.9; Book *book2 = [[Book alloc] init]; book2.name = @"蛙"; book2.price = 10; Book *book3 = [[Book alloc ] init]; book3.name = @"平凡的世界"; book3.price =5; NSArray *books = [[NSArray alloc] initWithObjects:book1,book2,book3, nil]; [author2 setValue:books forKey:@"issueBook"]; // 获取数组中所有book对象的书名 NSArray *bookNamArray = [author2 valueForKeyPath:@"issueBook.name"]; NSLog(@"bookNamArray: %@",bookNamArray); // 获取数组中所有book对象的价格 NSArray *priceArray = [author2 valueForKeyPath:@"issueBook.price"]; NSLog(@"priceArray: %@",priceArray); // 获取数组中book对象的个数 NSNumber *count = [author2 valueForKeyPath:@"issueBook.@count"]; NSLog(@"count= %@",count); // 计算数组中所有book对象的价格总和 NSNumber *num = [author2 valueForKeyPath:@"[email protected]"]; NSLog(@"sumofPrice= %@",num); // 计算数组中所有book对象价格的平均值 NSNumber *avg = [author2 valueForKeyPath:@"[email protected]"]; NSLog(@"avgofPrice= %@",avg); // 取得数组中所有book对象中价格的最大值 NSNumber *max = [author2 valueForKeyPath:@"[email protected]"]; NSLog(@"maxofPrice= %@",max); // 取得数组中所有book对象中价格的最小值 NSNumber *min = [author2 valueForKeyPath:@"[email protected]"]; NSLog(@"minofPrice= %@",min); } return 0; }运行结果如下: