Ios Cocos2d触摸调度器导致对象保留
我对cocos2d有问题。我上了一堂接受触摸的课。类是Ios Cocos2d触摸调度器导致对象保留,ios,cocos2d-iphone,touch,dealloc,Ios,Cocos2d Iphone,Touch,Dealloc,我对cocos2d有问题。我上了一堂接受触摸的课。类是CCLayer的子类,init看起来是这样的: - (id)initWithFrame:(CGRect)frameSize { self = [super init]; if (self) { frame = frameSize; size = frame.size; origin = frame.origin; [[[CCDirector sharedD
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
是类变量,但现在这并不重要。所以我注册了我的类witchtouchDispatcher
,它允许我处理触摸。触摸处理是这样完成的:
- (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
I中发布这个类
我遗漏了什么?你自己说的:当你在
addTargetedElegate
中将图层对象用作代理时,触摸调度器会保留它。因此,您必须从其他地方的dispatcher中取消注册层,否则将永远不会调用最终版本(因此不会调用dealloc
)
简而言之:如果代理是同一个对象,请不要从dealloc方法取消注册touch dispatcher要澄清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];
}