买粽子的例子,主要输练习KVC的应用,(注意:必须建立一个数组,才能使用KVC的运算)详细代码如下:
1.main函数代码:
#import <Foundation/Foundation.h> #import "Person.h" #import "zongZi.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); float money = 5.5; NSString * smoney = [NSString stringWithFormat:@"%.2f",money]; Person * suiping = [[Person alloc]init]; [suiping setValue:@"suiping" forKey:@"name"]; [suiping setValue:smoney forKey:@"money"]; zongZi * zongzi1 = [[zongZi alloc]init]; [zongzi1 setValue:@"大肉粽" forKey:@"name"]; [zongzi1 setValue:@"1.2" forKey:@"price"]; zongZi * zongzi2 = [[zongZi alloc]init]; [zongzi2 setValue:@"蜜枣粽" forKey:@"name"]; [zongzi2 setValue:@"0.7" forKey:@"price"]; zongZi * zongzi3 = [[zongZi alloc]init]; [zongzi3 setValue:@"豆沙粽" forKey:@"name"]; [zongzi3 setValue:@"0.8" forKey:@"price"]; //新建一个购物车 NSArray * gouwuche = [NSArray arrayWithObjects:zongzi3,zongzi2,zongzi1,zongzi1, nil]; //把购物车传进到数组moneyCollent中,(注意:必须建立一个数组,才能使用KVC的运算) [suiping setValue:gouwuche forKey:@"moneyCollent"]; float usedmoney = [[suiping valueForKeyPath:@"]; float shengXia = money - usedmoney; //进行KVC运算,方便快捷 NSLog(@"我刚开始有%@元", [suiping valueForKey:@"money"]); NSLog(@"总共买了%@个", [suiping valueForKeyPath:@""]); NSLog(@"总共花了%@元", [suiping valueForKeyPath:@""]); NSLog(@"剩下%.2f元", shengXia); NSLog(@"平均花了%@元", [suiping valueForKeyPath:@""]); NSLog(@"最便宜%@元", [suiping valueForKeyPath:@""]); NSLog(@"最贵的%@元", [suiping valueForKeyPath:@""]); } return 0; }
2.Person.h代码:
#import <Foundation/Foundation.h> #import "zongZi.h" @interface Person : NSObject @property (nonatomic,assign) NSString *name; @property (nonatomic,assign) float money; @property (nonatomic,assign) NSArray *moneyCollent;//(注意:必须建立一个数组,才能使用KVC的运算) @end
时间: 2024-10-04 12:38:50