I have read the memory management guide from Apple and I don’t see where this case is explained…
Many times, especially when writing a class method to return an instance of a class, I’ll start it out like this, because that’s how I’ve seen it done, and it works.
[NOTE] This code is from memory – I’ll update it when I get home to show an example that really works (I made this up to illustrate it, but obviously I don’t recall it well enough to construct something that makes sense…
[EDIT] Here’s my actual method – of course everyone was right that I must be calling alloc which I am.
+ (id)player
{
Player *player = nil;
if ((player = [[[super alloc] initWithFile:@"rocket.png"] autorelease])) {
[player setProjectileType:kProjectileBullet];
[player setProjectileLevel:1];
[player setInvincible:YES];
[player setEmitter:[CCParticleSystemQuad particleWithFile:@"exhaust.plist"]];
[[player emitter] setPosition:ccp(0.0, player.contentSize.height/2)];
[player addChild:player.emitter];
}
return player;
}
So what I got from the responses is:
* Declaring the instance just gets me a pointer to a memory location and tells Xcode what class the object will be.
* Setting the pointer to nil pretty much just sets it to zero – keeping it from having garbage in it (right?)
* Since I’m autoreleasing the instance, the object that is returned is also autoreleased.
Thanks for helping me understand this!
If you are really interested in what the compiler does, the answer is: the compiler will reserve some memory on the stack for the local variable
aDooDad, which is a pointer type (it is generally 64 or 32 bits in size depending on the processor). That pointer is then initialized to containnil(usually0x00..00).A statement like this:
makes use of pointer variable
aDooDadto store the address in memory of the object that is further allocated (which is the address of memory reserved byalloc).So, in the end,
is not declaring an object, just a variable whose content is interpreted as the address of an object of
DooDadtype. Such declaration, therefore, is just like any other declaration you know, e.g. when initializing anintto 0, so that later you can assign it some value in anifstatement.A statement like:
is interpreted by the Objective-C runtime system like: send message
doSomethingto the object whose address is stored inaDooDad. If that address isnilno message is sent. On the other hand, if you dereference a nil pointer:*aDooDadyou’ll get undefined behavior.Pointers are pretty low level stuff. I hope this helps.