Print out the name of object instance


#1

What would be the best way of printing out the name of an instance variable in the for loop. For instance so output would resemble:

stock1 price: 5000 stock2 price: 2000 stock3 price: 1000 etc..

This very well may be answered later on in the book or very well could have already been answered in the book. I assume I would have to use the idea of self?


#2

You can’t get the name of the variable at runtime. Weird, right? You can get the value of the variable, but not its name or type.


#3

thats very interesting! I just assumed you could based on my limited, beginner knowledge of ruby. Thanks for the reply. Ive learned a lot more from using the message board in conjunction with the book.


#4

Dang wish I would have read that an hour ago. I solved it by creating symbolOfStock for each instance of StockHolding.


#5

Dang wish I would have read that an hour ago. I solved it by creating symbolOfStock for each instance of StockHolding.[/quote]

Yeah, I did the same as mhohman. For anyone wanting to have the name of the stock show when they iterate through the array, it is very satisfying :slight_smile: , here is how I did it.

Add the instance variable NSString *stockName; and @property NSString *stockName; to the StockHolding.h file

then add @synthesize stockName; to your StockHolding.m file

once in main when you are creating instances of StockHolding you can add your new instance variable to the mix [code] @autoreleasepool {

    StockHolding *Apple = [[StockHolding alloc]init];
    
    [Apple setPurchasedSharePrice:100.0];
    [Apple setCurrentSharePrice:602.17];
    [Apple setNumberOfShares:32];
    [Apple setStockName:@"Apple"];[/code]

and to get it to print when intreating through the array, I did this NSUInteger stockscount = [stocks count]; for (int i = 0; i < stockscount; i++) { StockHolding *x = [stocks objectAtIndex:i]; NSString *q = [x stockName]; float z = [x valueInDollars]; float y = [x costInDollars]; float w = [x valueInDollars] - [x costInDollars]; NSLog(@"Here is what %@ cost me %.2f, this is what is worth now %.2f, and this is how much I have made from %@ %.2f",q, y, z, q, w); }

I’m sure there is a more efficient way to do this but it was a fun journey and so much more rewarding to see the stock names in the log.


#6

and just for the record, I wish I had 32 shares of apple stock :slight_smile: but I do not.