objective-ciosnsnumberformatternsenumerator

Counting currency from NSDictionary objects


The basic idea is to iterate through a directory full of .plists which have NSDictionary objects that contain a monetary value.

Question

How can I iterate through all of the directory contents and extract all the "Current Value" objects and add them together to get a total amount?

Example

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);       
} 

Current output

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

Desired output

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

Solution

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);  

Solution Output

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

Solution

  • Couldn't you just keep a running total or did I miss it?

    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);