Cocos2d触摸派发器导致对象保留

4

我有一个关于cocos2d的问题。我创建了一个接收触摸的类。这个类是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个回答

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

3
你自己说了:触摸分派器在addTargetedDelegate中使用你的层对象作为代理时会保留它。因此,你必须从其他地方注销你的层,否则最终释放将永远不会被调用(因此dealloc也不会被调用)。
简而言之:如果委托是同一对象,请勿从dealloc方法中注销触摸分派器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接