Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocos2d touch dispatcher causing object retain

I have a problem with cocos2d. I made a class which receives touches. Class is a subclass of CCLayer and init looks like so:

- (id)initWithFrame:(CGRect)frameSize
{
    self = [super init];
    if (self)
    {
        frame = frameSize;
        size = frame.size;
        origin = frame.origin;
        [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
    }
    return self;
}

So everything is kept simple. frame, size and origin are class variables but this does not matter right now. So I register my class witch touchDispatcher which allows me to handle touches. The touch handling is done like so:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    return YES;
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    //Some touch logic which i need.
}

And in dealloc I release all the retained information and unregister from touchDispatcher. But the dealloc is never called. If I dont register with touchDispatcher the dealloc is called properly. If important, this class is added as a child in another CCLayer subclass and in that class's dealloc I release this one.

What am I missing?

like image 590
Majster Avatar asked Dec 27 '22 12:12

Majster


1 Answers

to clarify giorashc's answer, do this. :

- (void)onEnter {
    [super onEnter];
    [[CCDirector sharedDirector].touchDispatcher addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

- (void)onExit {
    // called before the object is removed from its parent
    // force the director to 'flush' its hard reference to self
    // therefore self's retain count will be 0 and dealloc will
    // be called.
    [super onExit];
    [[CCDirector sharedDirector].touchDispatcher removeDelegate:self];
}
like image 167
YvesLeBorg Avatar answered Jan 07 '23 23:01

YvesLeBorg