NSMutableArray enumerating objects [closed]

2020-05-09 17:47发布

问题:

How can I enumerate the values of the instances in this code through fast enumeration, It's returning addresses of the arrays, and also I feel like there is a short way for doing this.

BNRStockHolding *stockHolding = [[BNRStockHolding alloc] init];
[stockHolding setPurchasedSharePrice:2.30];
[stockHolding setCurrentSharePrice:4.50];
[stockHolding setNumberOfShares:40];
float p = [stockHolding purchasedSharePrice];
float c = [stockHolding currentSharePrice];
int n = [stockHolding numberOfShares];
float cost = [stockHolding costInDollars];
float val = [stockHolding valueInDollars];

BNRStockHolding *stockHolding1 = [[BNRStockHolding alloc] init];
[stockHolding setPurchasedSharePrice:12.19];
[stockHolding setCurrentSharePrice:10.56];
[stockHolding setNumberOfShares:90];
float p1 = [stockHolding purchasedSharePrice];
float c1 = [stockHolding currentSharePrice];
int n1 = [stockHolding numberOfShares];
float cost1 = [stockHolding costInDollars];
float val1 = [stockHolding valueInDollars];

BNRStockHolding *stockHolding2 = [[BNRStockHolding alloc] init];
[stockHolding setPurchasedSharePrice:45.10];
[stockHolding setCurrentSharePrice:49.51];
[stockHolding setNumberOfShares:210];
float p2 = [stockHolding purchasedSharePrice];
float c2 = [stockHolding currentSharePrice];
int n2 = [stockHolding numberOfShares];
float cost2 = [stockHolding costInDollars];
float val2 = [stockHolding valueInDollars];

NSMutableArray *threeInstances = [NSMutableArray arrayWithObjects:
    stockHolding, stockHolding1, stockHolding2, nil];

for(BNRStockHolding *d in threeInstances) {
    NSLog(@"%@", d);
}

回答1:

If you don't want to modify your BNRStockHolding class, it'd look something like this:

for(BNRStockHolding *d in threeInstances) {
    NSLog(@"Number of shares: %d", [d numberOfShares]);
    NSLog(@"PurchasedSharePrice: %f, CurrentSharePrice: %f", [d 
        purchasedSharePrice], [d currentSharePrice]);
}


回答2:

Do you just want to print the objects? If so try defining the description method in your BNRStockHolding class. Like this:

- (NSString *)description {
    return [NSString stringWithFormat: @"PurchasedSharePrice=%f, CurrentSharePrice=%f", purchasedSharePrice, currentSharePrice];
}

Instead of printing the addresses it will print out the NSString you defined in there.