Hi-Jack Optimizations (aka "Sub-Classing")

Did you know that you can take control of just about any of the Corona SDK’s pre-made functions attached to display objects?

That’s right, you can actually replace some of the built-in functions with your own. This is known as hi-jacking, and it can come in very, very handy in many instances.

There’s one little performance (or even better, crash-prevention) “trick” I’m going to show you that will involve hi-jacking Corona’s built-in removeSelf() method that’s attached to every display object.

Here’s the code:

local myObject = display.newImage( "myimage.png" )
myObject.x, myObject.y = 100, 200

local myObject:enterFrame = function( event )
    print( "This is your runtime listener!" )
end

Runtime:addEventListener( "enterFrame", myObject )

-- The line below will "cache" the original removeSelf function
-- so it is still able to be used:
myObject.oldRemoveSelf = myObject.removeSelf

-- Let the hi-jacking begin:
function myObject:removeSelf()

    -- new stuff we're adding:
    Runtime:removeEventListener( "enterFrame", self )

    -- call the original removeSelf() function:
    myObject:oldRemoveSelf()
    myObject = nil
end

See the above code with syntax highlighting here.

If you go line-by-line, you can probably figure out what I did. I “hi-jacked” the built-in removeSelf() function for myObject, and added a call to Runtime:removeEventListener() before proceeding to call the original removeSelf() function.

Of course, it’s just a simple example, but you can probably see where the above might come in handy. Runtime listeners must be removed manually, as I describe in both my managing runtime listeners and memory 101 articles.

However, sometimes Runtime listeners are hard to keep track of (especially if your app is a significant size), and if you have a lot attached to objects (as I do in the example I gave above), some might slip through.

The above “hi-jacking” example basically makes sure the associated Runtime listener is removed along with the object whenever you call removeSelf(). It’s very handy!

I’ve used hi-jacking plenty times to add to plenty of Corona’s built-in functions. What other hi-jacking uses, besides cleaning up Runtime listeners, can YOU think of?

To read more entries, visit the archives or subscribe to the RSS feed.