【发布时间】:2013-04-06 18:53:49
【问题描述】:
我正在尝试找出修复我的应用程序中的内存泄漏并使用外部类的最佳方法。我在 Corona SDK 中编码并使用 Storyboard。当我通过类创建对象时,我认为我没有正确删除它们。你能看看下面的帮助吗
1) 在代码的底部,我展示了如何移除键盘。这是否足够,还是我需要做更多,因为键盘是通过另一个文件创建的?
2) 在keyboard.lua 中,我需要以keyboard.lua 文件稍后可以使用函数操作它们的方式创建对象。我通过声明 theKeyboard、theCursor、theBackground 来做到这一点。
与调用它们 M.theKeyboard、M.theCursor、M.theBackground 相比,有什么理由这样做而不是因为 M 是本地的而不提前声明它们?
3) 你会以不同的方式实现这个键盘类吗?如果有,可以指点一下吗?
这里是示例代码。我想在我的应用程序中重用这个键盘代码。任何时候都应该只有一个键盘。我想在用户退出场景时完全移除键盘,因为许多屏幕不需要键盘。
-- keyboard.lua
local M = {}
local theKeyboard, theCursor, theBackground
function M.newBackground()
if theBackground then
theBackground = nil
end
local newBackground = display.newRect(0,0,0,0)
-- set position, size, color, etc
theBackground = newBackground
return newBackground
end
... many other functions to create cursor, textlabels, etc
function M.newKeyboard()
if theKeyboard then
theKeyboard = nil
end
theKeyboard = display.newGroup()
theCursor = M.newCursor()
theBackground = M.newBackground()
-- lots more stuff... like I create buttons for each key on the keyboard
theKeyboard:insert(theCursor)
theKeyboard:insert(theBackground)
return theKeyboard
end
function M.removeKeyboard()
display.remove(theCursor)
display.remove(theBackground)
display.remove(theKeyboard)
theCursor = nil
theBackground = nil
theKeyboard = nil
end
return M
然后我的应用使用了故事板,所以这里是我如何将键盘集成到场景中的示例。
local keyboard = require ( "keyboard" )
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local keyboardGroup, otherobjects
function scene:createScene( event )
local group = self.view
keyboardGroup = keyboard.newKeyboard
group:insert( keyboardGroup )
end
end
-- other code
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
local group = self.view
-- Is this sufficient for removing the keyboard completely?
keyboard.removeKeyboard()
keyboardGroup = nil
end
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- additional code that comes with storyboard
return scene
【问题讨论】:
-
我没有检查代码,但是在开始之前,请问您是否在enterframe函数中使用了垃圾收集器?因为没有它,您可能会遇到一些内存问题
-
我没有使用垃圾收集器。我不知道有一个。但即便如此,我还是想先修复所有内存泄漏,然后在万不得已时使用垃圾收集器
标签: oop memory-leaks lua coronasdk