【问题标题】:Integrate UIView to cocos2d: how to release UIView elements?将UIView集成到cocos2d:如何释放UIView元素?
【发布时间】:2011-06-09 16:19:17
【问题描述】:
如果我将 UITextField 添加到 openGLView 并再次将其删除,则永远不会调用 dealloc。
// add a textfield to the openGLView
codeTextfield = [[UITextField alloc] initWithFrame:codeTextfieldFrame];
[[[CCDirector sharedDirector] openGLView] addSubview:codeTextfield];
// remove the textfield
[codeTextfield removeFromSuperview];
// call replaceScene
[CCDirector sharedDirector] replaceScene:[Menu node]];
// dealloc will not be called
我被这个问题困扰了很长时间,但目前还没有解决方案。
【问题讨论】:
标签:
iphone
cocoa-touch
memory-management
uiview
cocos2d-iphone
【解决方案1】:
沿途检查保留计数;这应该可以帮助您了解发生了什么。
codeTextfield = [[UITextField alloc] initWithFrame:codeTextfieldFrame];
// RETAIN COUNT IS NOW 1
[[[CCDirector sharedDirector] openGLView] addSubview:codeTextfield];
// RETAIN COUNT IS NOW 2
[codeTextfield removeFromSuperview];
// RETAIN COUNT IS NOW 1
要在从视图中删除 codeTextfield 后将计数恢复为 0,请改为执行以下操作:
codeTextfield = [[UITextField alloc] initWithFrame:codeTextfieldFrame];
// RETAIN COUNT IS NOW 1
[[[CCDirector sharedDirector] openGLView] addSubview:codeTextfield];
// RETAIN COUNT IS NOW 2
[codeTextfield release];
// RETAIN COUNT IS NOW 1
[codeTextfield removeFromSuperview];
// RETAIN COUNT IS NOW 0 -- DEALLOC WILL BE CALLED
【解决方案2】:
addSubview 保留视图。当您使用alloc 创建对象时,您也拥有它。删除视图只会将保留计数减少 1。在将其添加为子视图后,您需要 [codeTextfield release]。