Jem
Jem

Reputation: 6406

Autorelease: Must [ retain] on member variables?

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.

Upvotes: 0

Views: 216

Answers (2)

Sakares
Sakares

Reputation: 606

If you would like to maintain keyNodes object until BasicEngine is available, you can also implement with singleton pattern to make them static.

see also : http://xperienced.com.pl/blog/3-ways-to-implement-singleton-pattern-in-objective-c

Upvotes: 0

kevboh
kevboh

Reputation: 5245

retain implies ownership of the retainer on the retainee. Since keyNodes is a class member, your engine "owns" it, and thus should retain on it.

Under the hood retain is incrementing the reference count on keyNodes, which signals to the system that one more object is interested in keeping whatever keyNodes points to around in memory. Similarly, you're expected to call release on keyNodes in your dealloc method, which will decrement the retain count as your engine no longer "owns" keyNodes.

Upvotes: 2

Related Questions