2014-01-15 28 views
-3

我已经编写了代码 - 但我需要一些说明,我无法在本网站的其他答案中找到一些说明。我无法找到一个可靠的例子来帮助我。遍历数组以打印出每个值

这是否正确地认为通过我的数组“迭代”?我觉得这真的是硬编码。我仍在学习。谢谢

NSMutableArray *stocks = [NSMutableArray array]; 


    BNRStockHolding *A = [[BNRStockHolding alloc]init]; 
    BNRStockHolding *B = [[BNRStockHolding alloc]init]; 
    BNRStockHolding *C = [[BNRStockHolding alloc]init]; 


    [stocks insertObject:A atIndex:0]; 
    [stocks insertObject:B atIndex:1]; 
    [stocks insertObject:C atIndex:2]; 

    for (int i = 0; i < 1; i++) 
    { 

    { 
    [A setNumberOfShares:40]; 
    [B setNumberOfShares:90]; 
    [C setNumberOfShares:210]; 

    [A setPurchaseSharePrice:2.30]; 
    [B setPurchaseSharePrice:12.19]; 
    [C setPurchaseSharePrice:45.10]; 

    [A setCurrentSharePrice:4.50]; 
    [B setCurrentSharePrice:10.56]; 
    [C setCurrentSharePrice:49.51]; 

    float costA = [A costInDollars]; 
    float costB = [B costInDollars]; 
    float costC = [C costInDollars]; 
    NSLog(@"This stock costs %.2f", costA); 
    NSLog(@"This stock costs %.2f", costB); 
    NSLog(@"This stock costs %.2f", costC); 

    NSLog(@"\n"); 

    float valueA = [A valueInDollars]; 
    float valueB = [B valueInDollars]; 
    float valueC = [C valueInDollars]; 
    NSLog(@"The current value of this stock is %.2f", valueA); 
    NSLog(@"The current value of this stock is %.2f", valueB); 
    NSLog(@"The current value of this stock is %.2f", valueC); 
    } 
    } 

回答

1

你目前的循环实际上并没有循环任何事情。如果你想通过数组进行迭代,打印出的每个值,这里就是你要做的:

for(BNRStockHolding *stockHolding in stocks) { 

    NSLog(@"This stock costs: %.2f", [stockHolding costInDollars]); 
    NSLog(@"The current value of this stock is %.2f", [stockHolding valueInDollars]); 
} 

这确实是一个基本的概念。在尝试编写完整的应用程序之前,我会通过this回答关于循环基础知识的回答(也许还会回顾一些其他基础知识)。