I have a function that takes another function as a parameter. Something like that:
public function onHits(target : Shape, callback : Function) : void
I use it by passing a member function as a parameter, which should be called whenever the passed object hits. A function is called multiple frames. Therefore, it is used:
Function on hit:
public function onHitCB(hitObject : *) : void {
When I do this, I get a memory leak. I highlighted the problem for this onHits method and commented on everything else. onHits is an empty method without code inside it, onHitCB is also empty. If I comment on the onHits call, there is no memory leak, and if I pass null instead of onHitCB, there will be no memory leak.
So, this is clear when I pass onHitCB as a parameter, which is the problem. Therefore, I thought that this could be because Flash allocates some memory to create the Function pointer and does not release it, but I call System.gc () every frame in debug mode, and the leak still exists. This would mean that it is either an error in the SDK, or I am not doing anything right.
I found a strange workaround by storing a variable that points to the function that I assign in the constructor of my object:
private var func : Function; public function MyObject() { func = onHitCB; }
and this will clear the memory leak even if I still pass onHitCB as a parameter . Does this mean that this is not a getter function to get onHitCB, but something else that causes a memory leak?
I am very confused. How can this cause a memory leak:
public function MyObject() { } public function update() : void { CollisionManager.onHits(myShape, onHitCB);
but not that?
private var func : Function; public function MyObject() { func = onHitCB; } public function update() : void { CollisionManager.onHits(myShape, onHitCB);
and is there any way not to do this workaround?