Cocos2d触摸调度程序导致对象保留

时间:2012-12-24 15:09:43

标签: ios cocos2d-iphone touch dealloc

我遇到cocos2d问题。我做了一个接受触摸的课程。 Class是CCLayer的子类,init看起来像这样:

- (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;
}

所以一切都很简单。 framesizeorigin是类变量,但现在无关紧要。所以我注册了我的班级女巫touchDispatcher,它允许我处理触摸。触摸处理完成如下:

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

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

dealloc中,我会释放所有保留的信息,并从touchDispatcher取消注册。但dealloc从未被调用过。如果我没有注册touchDispatcher,则dealloc被正确调用。如果重要的话,这个类将作为子类添加到另一个CCLayer子类中,并且在该类dealloc中我将释放此类。

我错过了什么?

2 个答案:

答案 0 :(得分:7)

澄清giorashc的答案,这样做。 :

- (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];
}

答案 1 :(得分:3)

您自己说过:触摸调度程序保留您的图层对象,因为您在addTargetedDelegate中将其用作委托。因此,您必须从其他地方的调度程序中取消注册您的图层,否则最终版本将永远不会被调用(因此不会调用dealloc)。

简而言之:如果委托是同一个对象,请不要从dealloc方法取消注册触摸调度程序