从NSDictionary对象计数货币

时间:2012-05-07 03:18:23

标签: objective-c ios nsnumberformatter nsenumerator

基本思想是遍历一个充满.plists的目录,这些目录包含一个包含货币值的NSDictionary对象。

问题

如何遍历所有目录内容并提取所有“Current Value”对象并将它们添加到一起以获得总金额?

实施例

NSArray * itemList = [MANAGER contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",INVENTORY_PATH] error:nil];
for ( NSString * item in itemList )
{
    NSDictionary * currentItem = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",INVENTORY_PATH, item]];

    float monetaries = [[currentItem objectForKey:@"Current Value"] floatValue];

    NSLog(@"Current Value: %.2f",monetaries);       
} 

当前输出

2012-05-06 22:11:33.583 WrightsCS[3151:15803] Current Value: 350.99
2012-05-06 22:11:33.584 WrightsCS[3151:15803] Current Value: 321.54

期望的输出

2012-05-06 22:11:33.584 WrightsCS[3151:15803] Total Value: 672.53

解决方案

float total = 0.0f ;
float monetaries = 0.0f;

NSArray * itemList = [MANAGER contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",INVENTORY_PATH] error:nil];
for ( NSString * item in itemList )
{
    NSDictionary * currentItem = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",INVENTORY_PATH, item]];

    monetaries = [[currentItem objectForKey:@"Current Value"] floatValue];
    total += monetaries ;     

    NSLog(@"Current Value: %.2f",monetaries);  
}    

NSLog(@"Total Value: %.2f",total);  

解决方案输出

2012-05-06 22:26:05.460 WrightsCS[3205:15803] Current Value: 350.99
2012-05-06 22:26:05.462 WrightsCS[3205:15803] Current Value: 321.54
2012-05-06 22:26:05.462 WrightsCS[3205:15803] Total Value: 672.53

1 个答案:

答案 0 :(得分:1)

难道你不能保持一个总计还是我想念它?

NSArray * itemList = [MANAGER contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",INVENTORY_PATH] error:nil];

float total = 0.0f ;
for ( NSString * item in itemList )
{
    NSDictionary * currentItem = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",INVENTORY_PATH, item]];

    float monetaries = [[currentItem objectForKey:@"Current Value"] floatValue];
    total += monetaries ;
//    NSLog(@"Current Value: %.2f",monetaries);       
} 

NSLog(@"Total Value: %.2f",monetaries);