removing image from a group seems to destroy it

I’m trying to cache some images inside my app, but they seem to be destroyed after they are removed from the group that contained them (either by me or director.lua).

So what is supposed to happen to an image object in this scenario?

[lua]local group = display.newGroup()
local img = display.newImage(“image.png”)
– use a second reference to prevent garbage collection
local img2 = img
group:insert(img)
print(img.width) – prints 320

group:remove(1)
– or: img:removeSelf()
– or: display.remove(img)

print(img.width) – prints nil
print(img2.width) – prints nil[/lua]

img2 still references the image object, so the object should not be garbage collected, even after it is removed from the display group. But instead the object gets destroyed and img2 is now pointing to an empty table regardless of how the image is removed from the group (with img:removeSelf(), display.remove(img), or group:remove(1)).

Is this normal and expected? If it is, how do I cache an image object to prevent Corona from reloading it it from the disk when I want to use it again? Someone suggested not adding it to a display group, but I don’t think it’s practical.

Thanks for any tips!
Alex [import]uid: 36986 topic_id: 10795 reply_id: 310795[/import]

@wslab (Alex),
if you need to remove an image from the group and not from memory, then use the

display.stage:insert(img)

this will bring the ownership of img to the stage than the group that you had added it to.

now, if you want to remove img from memory, then use

img:removeSelf() or groupName:remove(imgIndex)
and also set img=nil for the GarbageCollector to clear up memory and deallocate these.

if you keep the reference, it will not get collected and therefore you will get a table 0x… and it will point to nil

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 10795 reply_id: 39253[/import]

@jayantv:

Thanks, that worked! I can save the image from destruction by putting it into another display group before calling director.changeScene()

Thinking about this, group:remove(index) and object:removeSelf() should probably be called group:destroy(index) and object:destroySelf() to better indicate what these functions really do.

[import]uid: 36986 topic_id: 10795 reply_id: 39535[/import]