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

所以一切都保持简单。frame,size并且origin是类变量,但现在这无关紧要。所以我注册了我的班级女巫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我发布了这个。

我错过了什么?

4

2 回答 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];
}
于 2012-12-24T15:40:39.297 回答
3

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

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

于 2012-12-24T15:22:02.077 回答