How to print instance name in fast enumeration?


#1

I am trying to use fast enumeration to print out my portfolio info. Especially the name of each stock (the instance names (objects) of the array)

NSArray *portfolio = [NSArray arrayWithObjects:stock_0, stock_1, stock_2, nil];

for (StockHoldings *stock in portfolio) {
            NSLog(@"%@ was purchased for %f, now worths %f, has a profit/loss of %f", stock, [stock costInDollars], [stock valueInDollars], [stock valueInDollars]-[stock costInDollars]);
        }

However, my output did not print “stock_0”, instead it prints: <StockHoldings: 0x10010a670>

<StockHoldings: 0x10010a670> was purchased for 9471.000000, now worths 10397.099609, has a profit/loss of 926.099609

One way to get around this is to add an variable in the class called stockName. But my question/point is: there gotta be a way to print the instance name. I looked posts in the board. It seems people simply ignore the stock identifiers and only prints the numbers.

Thank you very much, fellows!


#2

stock_0, stock_1, etc are the names of instance variables; they are not instance names. If you want to name your instances, you must declare properties and give values to them:

@interface Foo
...
@property (copy) NSString *name;
@end

You must also override the - description method of the class to write the instance name in the descritiption.


#3

Thank you so much for your reply, ibex10!

So I was right. I have to declare a variable to hold the name, just like price and numbers, etc.

And there is no way to call the “names of instance variables” in fast enumeration.?


#4

I am wondering the same thing. Since I have already given names to these object instances (e.g., stock1, stock2, stock3 in my code), is there a way to have NSLog display these instance variable names?


#5

Stop wondering. Objects do not have intrinsic names derived from the names of instance variables, unless you write extra code to equip them with names.


#6

Ok. Thanks.