KVC 的优点是能够强制的为没有提供接口的,私有的,受保护的属性去赋值,缺点就是打破了封装性,而且不能点出属性名字,属性名容易写错,写错就崩溃。
在book类声明字段
#import <Foundation/Foundation.h> #import "Author.h" @interface Book : NSObject { NSString * bookName; CGFloat bookPrice; Author * bookAuthor; NSMutableArray * allBooks; } @end
在 Author 类声明字段
#import <Foundation/Foundation.h> @interface Author : NSObject { NSString * authorName; } @end
在main 函数里
#import <Foundation/Foundation.h> #import "Book.h" int main(int argc, const char * argv[]) { @autoreleasepool { Book * book = [[Book alloc]init]; Author * author = [[Author alloc]init]; [author setValue:@"" forKey:@"authorName"]; [book setValue:author forKey:@"bookAuthor"]; [book setValue:@"巴金" forKeyPath:@"bookAuthor.authorName"]; [book setValue:@"《家 * 春 * 秋》" forKey:@"bookName"]; [book setValue:@32 forKey:@"bookPrice"]; NSLog(@"书本名:%@ 价格: %@ 作者:%@",[book valueForKey:@"bookName"],[book valueForKey:@"bookPrice"],[book valueForKeyPath:@"bookAuthor.authorName"]); //设置一组书本(KVC 为数组赋值) NSArray * GroupBookName = [NSArray arrayWithObjects:@"《百年孤独》", @"《英雄出少年》", @"《上年包青天》", @"《围城》", @"《家和万事兴》", nil]; NSArray * GroupBookPrice = @[@23,@32,@29,@42,@28]; NSArray * GroupBookAuthor = @[@"莫泊桑",@"默默",@"华仔键",@"佟丽娅",@"张飞"]; NSMutableArray * GroupBooks = [NSMutableArray arrayWithCapacity:5]; for (int i = 0; i < GroupBookName.count; i++) { Book * BOOK = [[Book alloc]init]; [BOOK setValue:GroupBookName[i] forKey:@"bookName"]; [BOOK setValue:GroupBookPrice[i] forKey:@"bookPrice"]; Author * author = [[Author alloc]init]; [BOOK setValue:author forKey:@"bookAuthor"]; [BOOK setValue:GroupBookAuthor[i] forKeyPath:@"bookAuthor.authorName"]; [GroupBooks addObject:BOOK]; } //kvc 为数组运算 for (Book * oneBook in GroupBooks) { NSLog(@"书名:%@ 作者:%@ 价格:%@",[oneBook valueForKey:@"bookName"],[oneBook valueForKeyPath:@"bookAuthor.authorName"],[oneBook valueForKey:@"bookPrice"]); } [book setValue:GroupBooks forKey:@"allBooks"]; //求平均价格 NSLog(@"%@",[book valueForKeyPath:@"allBooks.@avg.bookPrice"]); //求平最高价格 NSLog(@"%@",[book valueForKeyPath:@"allBooks.@max.bookPrice"]); //求最低价格 NSLog(@"%@",[book valueForKeyPath:@"allBooks.@min.bookPrice"]); //求所有价格之和 NSLog(@"%@",[book valueForKeyPath:@"allBooks.@sum.bookPrice"]); } return 0; }