我正在尝试找出修复我的应用程序中的内存泄漏并使用外部类的最佳方法。我在 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