Re: Newbie Question re Allocation & Initialization
Re: Newbie Question re Allocation & Initialization
- Subject: Re: Newbie Question re Allocation & Initialization
- From: Simon Wolf <email@hidden>
- Date: Tue, 20 May 2008 01:53:33 +0100
On 20 May 2008, at 01:18, 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?
Brad,
From one Cocoa newbie to another, here's my take on it...
newNumber is going to be used to store a number in memory and
therefore it needs to allocate or reserve an area of memory via the
alloc statement. numberToPrint is simply pointing to the already
reserved memory so you do not need to allocate an area of memory again
or initialise it a second time.
I'd recommend reading the Masters of the Void guide, particularly the
section on memory which you can find at http://masters-of-the-void.com/book5.htm
As you discovered, you can allocate memory for numberToPrint but you
are simply using up memory to store a value which is already stored
somewhere else.
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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