fun*_*ing 1 oop lua memory-leaks coronasdk
我正试图找出在我的应用程序中修复内存泄漏并使用外部类的最佳方法.我正在使用Corona SDK进行编码并使用Storyboard.当我通过类创建它时,我不认为我正在正确地删除对象.你能看看并帮助以下
1)在代码的底部,我展示了如何移除键盘.这是否足够,或者我需要做更多,因为键盘是通过另一个文件创建的?
2)在keyboard.lua中,我需要以keyboard.lua文件稍后可以使用函数操作它们的方式创建对象.我通过声明Keyboard,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
Run Code Online (Sandbox Code Playgroud)
然后我的应用程序使用故事板,所以这里是我如何将键盘集成到场景中的示例.
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
Run Code Online (Sandbox Code Playgroud)
请试试 -
if theKeyboard then
theKeyboard:removeSelf()
theKeyboard = nil
end
Run Code Online (Sandbox Code Playgroud)
我认为它会解决你的问题.