0

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?

Chewie The Chorkie
  • 4,896
  • 9
  • 46
  • 90
  • What do you mean by `Cocos2D` needs to keep the reference? Does it instantiate the variable for its own purpose? – Deepak Danduprolu Jun 28 '11 at 14:55
  • Yeah. If I were to release rushH and rushV right after I set the positions, the game will start fine, but if I move the map, it will crash immediately. No where in my own code am I referencing those objects until the player collides with them on the map, so Cocos2D must be using references of them to make rushH and rushV move with the map. – Chewie The Chorkie Jun 28 '11 at 15:04
  • Why don't you check if `rushH` and `rushV` are `nil` before you allocate them? Log them. – Deepak Danduprolu Jun 28 '11 at 15:06

2 Answers2

3

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.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
0

Make sure the optional variable is nil when its not needed, and do a nil check before dealloc'ing.

Perception
  • 79,279
  • 19
  • 185
  • 195