Say I have a BasicEngine class:
@interface BasicEngine : GfxEngine{
NSMutableDictionary *keyNodes;
AbstractVirtualJoystick *input0;
}
The related implementation goes as follows:
@implementation BasicEngine
- (id)init {
if ( (self = [super init]) ) {
keyNodes = [NSMutableDictionary dictionary];
}
return self;
}
My understanding is that calling [ dictionary] returns an autoreleased object. However, this dictionary should be kept in memory as long as the BasicEngine instance is available.
I realise I’m missing something as keyNodes quickly becomes a nil object.
Using [keyNodes retain] in the init method just helps, but I can’t understand why a class member needs to be retained.
Please help me understand this 🙂
Thanks.
retainimplies ownership of the retainer on the retainee. SincekeyNodesis a class member, your engine “owns” it, and thus shouldretainon it.Under the hood
retainis incrementing the reference count onkeyNodes, which signals to the system that one more object is interested in keeping whateverkeyNodespoints to around in memory. Similarly, you’re expected to callreleaseonkeyNodesin yourdeallocmethod, which will decrement the retain count as your engine no longer “owns”keyNodes.