Newbie Question re Allocation & Initialization
Newbie Question re Allocation & Initialization
- Subject: Newbie Question re Allocation & Initialization
- From: Brad Gibbs <email@hidden>
- Date: Mon, 19 May 2008 17:18:20 -0700
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 (email@hidden)
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:
This email sent to email@hidden