Any display object that you have added to the Composer scene’s “view” group (i.e. sceneGroup, self.view or scene.view depending on where you are scope wise) will be removed for you automatically when either:
-
composer.removeScene(“yourSceneInQuestion”) is called.
-
You have setup composer to auto dump scenes when you leave them. (https://docs.coronalabs.com/api/library/composer/recycleOnSceneChange.html)
-
You have setup processes do dump scenes when the memory is low. (https://docs.coronalabs.com/api/library/composer/recycleOnLowMemory.html)
In the case for #1. You don’t need to remove the objects yourself. Composer takes care of that for you. In the process, it will call your scene:destroy() event function, which is a place to dispose of audio you may have loaded during scene:create() or close databases/files you may have opened earlier. This function gets called well after your scene is no longer on screen.
Timers, physics, transitions, music etc. should be stopped/cancelled in scene:hide() since you don’t want them running after the scene leaves the screen (and conversely to make things line up right, those things should only be started in scene:show() or user action after the scene is on screen and running.
If you do call display.remove( someObject ), you should still nil out someObject.
Now to the OP’s real issue.
If you are holding a reference to an object in multiple places, you have to nil it out in multiple places:
hero = display…
enemy.targetedHero = hero
display.newImageRect() (or whatever display object you’re using) returns a pointer to a table that contains the object. Lets say the memory address for that table is 0x9483a122. The two lines of code above have basically created a simple variable named hero that contains the value 0x483a122. When you assign hero to enemy.targetedHero, you’re simply copying the value from here to the enemy.targetedHero attribute.
Now you come along and do either:
hero:removeSelf()
hero = nil
or
display:remove( hero )
hero = nil
The memory allocated to that table/object including the texture memory is freed up. The simple variable hero is now nil and no longer points to a memory address. All is happy. Except for the fact that enemy.targetedHero still contains the value 0x483a122 and thinks it’s pointing to a valid display object.
Your runtime function that’s looking at the enemy’s reference still thinks its good, when it’s not an your app blows up. Hiding the object if it’s not a lot of memory/resources is a perfectly valid method for this. If you need to bring that hero back, you can reset any values that need to be. Position it where you want it, make it visible again.
But you might want to make sure that if you go the remove method (needed if you’re eating a lot of memory or have a lot of objects), to make sure to clear all your references to the object.
Rob