買糉子的例子,主要輸練習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代碼:ui
#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