I’m getting a memory leak when I use a touch listener in my code.
local rnd = math.random
local absolute = math.abs
local score = 0
local check = 0
function addBall()
destroy = display.newRect( rnd(500), -150, 125, 125 )
destroy:setFillColor(255, 0, 0 )
collectgarbage("collect")
print("System Memory : "..collectgarbage("count"))
print("addball")
--transition.to( destroy, { time=1900, alpha=1, x=destroy.x, y=display.viewableContentHeight + 200 } )
function removeBall(obj)
obj:removeSelf()
obj = nil
addBall()
end
transition.to( destroy, { time=100, alpha=1, x=destroy.x, y=display.viewableContentHeight + 200, onComplete=removeBall } )
local function ballTouch(touch)
collectgarbage("collect")
print("System Memory : "..collectgarbage("count"))
print("balltouch")
print("removeBall")
removeBall(destroy)
end
destroy:addEventListener("touch", ballTouch)
collectgarbage("collect")
print("System Memory : "..collectgarbage("count"))
print("addlistener")
end
local timerBall = timer.performWithDelay(1000, addBall, 1)
If you run the code as is there’s no memory leak. But if you comment out the current transition and uncomment the other transition the code starts leaking.
One uses a touch listener and it leaks, the other does not.
This code is best viewed on the iphone 4 hardware.
Any thoughts on using the touch listener so that I don’t get a leak? Thanks as always in advance. [import]uid: 10903 topic_id: 4743 reply_id: 304743[/import]
When you call “allBall” here, you’re adding the same touch Listener over and over, but you never remove this Listener. Managing these Listeners is a key aspect of clean Lua code. If you have an object with a Listener, and it gets destroyed, you MUST destroy the Listener or it will forever remain in memory. If you retain the same object in memory, the Listener can remain “attached” to it, but once it goes, the Listener must be forcibly removed too.