The first loop is allocating an object an initializing it with the value of the loop variable (i) multiplied by 3.

The second loop is just assigning a pointer to that allocated object. It could have also been written :

for (i = 0 i < 10; i++)
{
    NSLog(@"The number at index %d is %@", i, [array objectAtIndex:i]);
}

that would get rid of the temporary variable and the author probably wanted to allow you to step through the code in the debugger and see the value retrieved from the array.

On May 19, 2008, at 8:18 PM, Brad Gibbs wrote:

On pages 36-7 of Aaron Hillegass' new book, he provides sample code for a Foundation Tool called Lottery. The code is below:

   NSMutableArray *array;
        array = [[NSMutableArray alloc] init];
        int i;
        for (i = 0; i < 10; i++) {
                NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i * 3)];
                [array addObject:newNumber];
        }
        
        for (i = 0; i < 10; i++) {
                NSNumber *numberToPrint = [array objectAtIndex:i];
                NSLog(@"The number at index %d is %@", i, numberToPrint);
        }

He allocates memory for and initializes the first two objects, array and newNumber. But, in the second 'for loop', numberToPrint is neither allocated nor initialized, but the program compiles and runs as expected. I replaced the second 'for loop' with the following, just to see what would happen:


        
        for (i = 0; i < 10; i++) {
                NSNumber *numberToPrint;
                numberToPrint = [[NSNumber alloc] init];
                numberToPrint = [array objectAtIndex:i];
                NSLog(@"The number at index %d is %@", i, numberToPrint);
        }
        

It compiled and ran as expected, too. But, when I tried to eliminate allocation and initialization for newNumber in the first 'for loop', the app threw an exception. I don't see an explanation in the book re why numberToPrint can be, but doesn't need to be allocated or initialized. Is it because numberToPrint is simply pointing to newNumber objects in the array that have already been allocated and initialized? Could someone please explain this?


Thank you.


Brad
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/fmcgeough%40mac.com

This email sent to [EMAIL PROTECTED]

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to