Aaron Hillegass(第17部分的练习)。
问题:在我的循环中,我希望它记录3个StockHolding
对象中每个对象的值,但是现在它只记录DHL
的值。如何让循环记录其他2个对象的值?
谢谢!
P.S。 StockHolding.h和StockHolding.m没事。
import <Foundation/Foundation.h>
import "StockHolding.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
StockHolding *DHL = [[StockHolding alloc] init];
[DHL setPurchaseSharePrice:345.67];
[DHL setNumberOfShares:23];
[DHL setCurrentSharePrice:389.23];
StockHolding *Sony = [[StockHolding alloc] init];
[Sony setPurchaseSharePrice:587.12];
[Sony setNumberOfShares:14];
[Sony setCurrentSharePrice:603.81];
StockHolding *EPAM = [[StockHolding alloc] init];
[EPAM setPurchaseSharePrice:178.45];
[EPAM setNumberOfShares:35];
[EPAM setCurrentSharePrice:190.64];
NSMutableArray *result = [[NSMutableArray alloc] initWithObjects:DHL, Sony, EPAM, nil];
for (NSObject *n in result) {
NSLog(@"Purchase for: %f\nNumber of shares: %d\nCurrent share price: %f\nCost,$: %f\nValue,$: %f\n", DHL.purchaseSharePrice, DHL.numberOfShares, DHL.currentSharePrice, DHL.costInDollars, DHL.valueInDollars);
}
}
return 0;
}
问题解决了:
#import <Foundation/Foundation.h>
#import "StockHolding.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
StockHolding *DHL = [[StockHolding alloc] init];
[DHL setNameOfShare:@"DHL"];
[DHL setPurchaseSharePrice:345.67];
[DHL setNumberOfShares:23];
[DHL setCurrentSharePrice:389.23];
StockHolding *Sony = [[StockHolding alloc] init];
[Sony setNameOfShare:@"Sony"];
[Sony setPurchaseSharePrice:587.12];
[Sony setNumberOfShares:14];
[Sony setCurrentSharePrice:603.81];
StockHolding *EPAM = [[StockHolding alloc] init];
[EPAM setNameOfShare:@"EPAM"];
[EPAM setPurchaseSharePrice:178.45];
[EPAM setNumberOfShares:35];
[EPAM setCurrentSharePrice:190.64];
NSMutableArray *result = [[NSMutableArray alloc] initWithObjects:DHL, Sony, EPAM, nil];
for (StockHolding *n in result) {
NSLog(@"\nName: %@\nPurchase for: %.2f\nNumber of shares: %lu\nCurrent share price: %.2f\nCost,$: %.2f\nValue,$: %.2f\n", n.nameOfShare, n.purchaseSharePrice, n.numberOfShares, n.currentSharePrice, n.costInDollars, n.valueInDollars);
}
}
return 0;
}
还有另一种选择:
[result enumerateObjectsUsingBlock:^(StockHolding *DHL, NSUInteger idx, BOOL *stop) {
NSLog(@"\nName: %@\nPurchase for: %.2fl\nNumber of shares: %lu\nCurrent share price: %.2fl\nCost,$: %.2fl\nValue,$: %.2fl\n", DHL.nameOfShare, DHL.purchaseSharePrice, (unsigned long)DHL.numberOfShares, DHL.currentSharePrice, DHL.costInDollars, DHL.valueInDollars);
}];
谢谢大家!
答案 0 :(得分:1)
我不确定你要做什么,但看起来代码末尾的for循环是错误的。我想你正试图为三个StockHolding
变量中的每一个运行NSLog?你写它的方式,它只是重复DHL的值3次。
请改为尝试:
for (StockHolding *n in result) {
NSLog(@"Purchase for: %f\nNumber of shares: %d\nCurrent share price: %f\nCost,$: %f\nValue,$: %f\n",
n.purchaseSharePrice,
n.numberOfShares,
n.currentSharePrice,
n.costInDollars,
n.valueInDollars);
}