Why does my output log out twice?


#1

why does the output log out twice?

@autoreleasepool
{
    
    StockHolding *apple = [[StockHolding alloc]init];
    [apple setCurrentSharePrice:100];
    [apple setPurchaseSharePrice:50];
    [apple setNumberOfShares:100];
    
    StockHolding *microSoft = [[StockHolding alloc]init];
    [microSoft setCurrentSharePrice:200];
    [microSoft setPurchaseSharePrice:100];
    [microSoft setNumberOfShares:100];
    
    
    NSArray *portFolio = [NSArray arrayWithObjects:apple, microSoft, nil];
    
    
    for (StockHolding *s in portFolio)
    {
        NSLog(@"Apple cost $%.2f to buy and it now worth $%.2f.  And MicroSoft cost $%.2f to buy and it now worth $%.2f", [apple costInDollars], [apple valueInDollars], [microSoft costInDollars], [microSoft valueInDollars]);
    }
    
    
    
    
}
return 0;

}


OUTPUT

2014-01-09 09:58:39.381 Stocks[1442:303] Apple cost $5000.00 to buy and it now worth $10000.00. And MicroSoft cost $10000.00 to buy and it now worth $20000.00
2014-01-09 09:58:39.383 Stocks[1442:303] Apple cost $5000.00 to buy and it now worth $10000.00. And MicroSoft cost $10000.00 to buy and it now worth $20000.00


#2

Hi Harpeet,

You have added two objects (apple and microsoft) to your array. So when you do a for in loop it will do the loop twice and thus log twice.

Further more in the NSLog line you refer to the original Stockholding object instead of the one that is stuff in the Portfolio array. So the correct log line should be something like…

NSLog(@“This share cost %.2f to buy and it is now worth %.2f.”, [s costInDollars], [s valueInDollars]);

Hope that helps…

JP