Enumerating through the Array In The Challenge


1st post have been slowly figuring out each challenge in the book, it seems i get pretty close to figuring it all out on my own but get stuck. In this challenge it was implementing the for loop to enumerate through the array. I figured it out by other peoples examples but i wanted to be clear in regards to how it actually works.

From my understanding when you run the for loop

the *i grabs the location of each object.

then after that it gets a little confusing. From answers i saw people would just send *i to what ever piece of the object instance within the array and basically get back each item. could you explain what is really going on?


Yes, you are right: i is assigned the address of each object in the array in turn. (And for each assignment, the block of code is executed.)

Once you have the address of an object stored in i, you can use i to send messages to the object:

int sum = 0; for (StockHolding *i in stocks) { sum = sum + [i valueInDollars]; } NSLog(@"My portfolio is worth %d dollars!", sum);


Ah thank you. that makes total sense now!