What if I want to alloc a class inside another and I want to reference it easily, but sometimes this class would not need to be alloc'd, therefore not dealloc'd. How is this done? Can I put a conditional inside dealloc so it doesn't have to be released?
In more detail, I'm using Cocos2D. I have player ability classes that may or may not need to be allocated. In my init:
// Abilities
if(abilityRushH == 0){
objects = [theMap objectGroupNamed:@"oj"];
startPoint = [objects objectNamed:@"item_ability_rushH"];
x = [[startPoint valueForKey:@"x"] intValue];
y = [[startPoint valueForKey:@"y"] intValue];
rushH = [[RushHorizontal alloc] init];
[self addChild:rushH.rushHSpriteSheet];
rushH.rushHSprite.position = ccp(x,y);
}
if(abilityRushV == 0){
objects = [theMap objectGroupNamed:@"oj"];
startPoint = [objects objectNamed:@"item_ability_rushV"];
x = [[startPoint valueForKey:@"x"] intValue];
y = [[startPoint valueForKey:@"y"] intValue];
rushV = [[RushVertical alloc] init];
[self addChild:rushV.rushVSpriteSheet];
rushV.rushVSprite.position = ccp(x,y);
}
Cocos2D needs to keep the reference so it can scroll with the map. But if I'm not alloc'ing it, how do I NOT dealloc?
Since you are talking of releasing it in dealloc
, there will be an instance variable for this. Now when any instance of an Objective-C class is allocated, all its objects are nil
and c types are set to 0 (or equivalent values). So you don't need to put any extra effort if the object of your class isn't instantiated as the instance variable will be nil
at dealloc
and so release
message sent to it will have no effect.