Want to clear some doubts regarding Garbage Collection ( AS3.0) - actionscript-3

package
{
public class SomeClass
{
public var myBtn:Button ;
public function SomeClass()
{
myBtn.addEventListener( MouseEvent.CLICK, clickFunction) ;
}
function clickFunction(e:Event){
}
}
}
Main Class:
var someClass:SomeClass = new SomeClass(); // step 1
addChild(someClass); // step 2
removeChild(someClass); // step 3
someClass = null // step 4
In the above, I want to completely destroy the someClass instance, so in step 4 it's been assigned null value.
Q1) Is step 4 ( assignment to null ) right way to destroy the instances ?
Q2) I referred : http://gskinner.com/blog/archives/2006/06/as3_resource_ma.html using delete keyword for objects. But i don't think delete keyword can be used for class instances ? How to use it in this case then ?
Q3) What happens to myBtn eventListener in SomeClass. Should i add a removeEventListener manually, before destroying instances of SomeClass. Or would it get destroyed automatically ?
Thanks

1/ Yes. (I assume the someClass variable is an instance variable)
2/ delete does not only remove the value of a variable, but even the variable definition. Since classes in AS3 are sealed in general, it won't work. I.e. delete should only be used on dynamically created members. Mainly "keys" of Object or Dictionary instances. But obviously you can remove the member definition of any class marked as dynamic using delete.
3/ Yes, always remove event listeners manually. You can create weakly referenced event listeners when registering the handler as a listener, but it's best to always make sure event listeners are removed manually, it's more readable, clear and fail-safe.
I tend to have a destroy method in all my classes, which can be called by the instance owner when it's cleaning up its references to a certain instance. This destroy method will unregister all event listeners, nullify instance members and do all kinds of cleanup.

The SomeClass instance you created will get garbage-collected after there are no longer any references to it. By setting your variable to null, it removes that reference, and the SomeClass instance will get garbage-collected as long as there are no more references to it.
In the code above, you do not need to remove the event listener. When a SomeClass instance is collected, all of its member variables will be collected (unless they're referenced elsewhere). Because the event listener has been added to the button, it will be collected when the button is collected.
Something to note, however: if instead of myBtn.addEventListener you had used stage.addEventListener, the stage would retain a reference to your callback function and you could end up with a memory leak. Always remove event listeners that are assigned to objects that will still be around after you care about the listener.
Creynder's advice is good: remove event listeners as a matter of habit. It's only really necessary, however, when an event listener's dispatcher is going to hang around but you don't want the callback to stay in memory.

Related

Set event.target to null

I want to nullify the event.target for garbage collection as the moveclip is no longer needed. What I have roughly is this:
mc.addEventListener(MouseEvent.CLICK, destroy);
public function destroy(event:MouseEvent):void {
event.target.parent.removeChild(event.target);
event.target.removeEventListener(MouseEvent.CLICK, destroyShape);
event.target = null; //THIS IS WHAT I WANT TO ACHIEVE
}
I'm sure this is relatively simple but I'm not sure how to do it.
thanks
You can't change MouseEvent.target value. It's a read only property. If your MovieClip doesn't exist (removeChild) and you removed event handler
mc.removeEventListener(MouseEvent.CLICK, destroy);
then the garbage collector automatically will remove it.
What you are trying to achieve (if it was even possible) would achieve nothing in term of Garbage Collection.
Unless redispatched the event will be garbage collected as soon as the method is done running. All properties of the event will also be discarded. This garbage collection of the event itself and its properties will have absolutely NO EFFECT on the object they point to in term of Garbage collection.
In the scope at which the event was dispatched in the first place the object will continue to exist after the event itself has been discarded. That is at that scope that the object reference must be nullified, not at the event listener scope where it will have no effect since the object still exists at the dispatching scope.
The solution accepted also does nothing. It is as relevant as applying a bandage to a wooden leg. Any local variable in function/method qualify for GC immediately after the method runs. Nullifying those variables has no effect whatsoever and does not constitute a valid answer to any problem and certainly not a GC problem. That those variables are GC does also not constitute a guaranty that the object they point to will be GC.
This is a case where a question about an inexistent and misunderstood problem is asked and answered by posting a false and irrelevant solution.
Case in point: Only a DisplayObject currently in a display list and attached to the stage has the ability to be the target of a MouseEvent. It is simply impossible for that object to become available for garbage collection before it is removed from the display list it belongs to. For those reasons that object cannot qualify for GC at the time the MouseEvent listener runs since that object still has at least one strong reference because it is attached to a display list. This is the proof that what the PO asks is misguided and any code examples are misguided as well since they cannot qualify the object for GC at that point in time.
As #subdan states, the target property of any Event is a readonly property.
You can still null your movie clip but not like in your sample.
mc.addEventListener(MouseEvent.CLICK, destroy);
public function destroy(event:MouseEvent):void
{
var myMC:MovieClip = event.target as MovieClip;
if( myMC )
{
myMC.removeEventListener(MouseEvent.CLICK, destroyShape);
myMC.parent.removeChild(myMC);
myMC = null; //THIS IS WHAT I WANT TO ACHIEVE
}
}

Custom Event Listener- un able to understand reasoning behind constance variable

I was following a tutorial online to create a custom event listener. i have some of an understanding of how it works, but its still somewhat confusing. i know that public static Constance DEAD:String = "dead" is a variable (a string) that equals the value "dead", however i do not understand why you need to create this variable just so (type:String) can turn into (DEAD:String). for instance, if you get the value "dead" is that just a default value since it could literally be anything? thanks.
package
{
import flash.events.Event;
public class AvatarEvent extends Event
{
public static const DEAD:String = "dead";
public function AvatarEvent( type:String )
{
super( type );
}
}
}
The value of the string is used by the EventDispatcher to identify the listeners to be notified when the event is dispatched.
The constant is for you, developer, to help you to write clean code, and avoid to create some silly bugs. When writing
dispatchEvent(new AvatarEvent(AvatarEvent.DEAD))
you avoid the typo that could occur in
dispatchEvent(new AvatarEvent(“dead”))
and allow the compiler to check the parameter you give to your event's constructor.
To go further, you could use Robert Penner's AS3Signals, which was written as a replacement for AS3 custom events. It solves many of the drawbacks of the custom events. By example, it does not use strings to identify events, so you can't have any conflict created by two events with the same type value. And it avoids creating a new object each time you want to dispatch a new event, so it is better for performances.

Using retain and release for Objects

Are there any general guide lines for using retain and release for objects in cocos2d-X ? When creating objects in a function, is it true that the functions memory is cleaned up the second the function returns. When a object is created, calling the retain function of the object, will retain object beyond the function return ?
Kind Regards
Generally in c++ you have this behaviour:
void foo() {
Object a;
Object *pA = new Object();
(…)
}
This would result in a being destroyed automatically at function end, as it was allocated on stack. The *pA would not get destroyed, as it was allocated on the heap (thus, you only loose the reference to it, but the object itself still lives).
Cocos implements a thing called "Automatic Reference Counting" : each CCObject has a reference counter and two methods retain() and release(). The way this works is, that every time you create an object, it gets registered in cocos structers (CCPoolManager). Then with every frame (between them being drawn) there is a maintenance loop which checks the reference counter of all objects : if it is 0 this means (to cocos) that no other objects reference it, so it is safe to delete it. The retain count of an object is automatically incresead when you use this object as an argument for an addChild function.
Example :
void cocosFoo() {
CCSprite *a = CCSprite::create(…);
CCSprite *b = CCSprite::create(…);
this->addChild(b);
}
What happens here is this :
Two CCSprites are created, cocos knows about them.
The b sprite is added to this object (say a CCLayer)
The function ends, no objects are destroyed (both of them being on heap).
Somewhere between this and next frame, the maintanance gets run. Cocos chcecks both sprites and sees that a has reference count == 0, so it deletes it.
This system is quite good, as you don't need to worry about memory management. If you want to create a CCSprite (for example), but not add it as a child yet, you can call retain() on it, which will raise its reference counter, saving it from automatic deletion. But then you'd have to remember about calling release() on it (for example, when adding it as a child).
The general things you have to remeber about are :
Each call to retain() by you needs to be paired with release().
You generally shouldn't delete CCObjects yourself. If you feel that you need to, there is a conveniece macro : CC_SAFE_DELETE(object)
So to answer your questions in short :
Are there any general guide lines for using retain and release for objects in cocos2d-X ?
Yes, you should generally not need to do it.
When creating objects in a function, is it true that the functions memory is cleaned up the second the function returns.
Answer to this is the whole text above.
When a object is created, calling the retain function of the object, will retain object beyond the function return ?
Yes, as will adding it as a child to another (retained in any way) object.
Here is the thing,
cocos2dx has an autorelease pool which drains the objects which have retain count=0 which is a variable to keep in check the scope of the cocos2dx object.
Now when you create new object using the create method it is already added to the autorelease pool and you don't need to release it or delete it anywhere , its like garbage collector in java, takes care of garbage objects behind your back.
But when you create new object using 'new' you definitely need to release it in its destructor or after its use is over.
Second thing,
when your object is added to the autorelease pool but you need it somewhere else you could just retain it , this increments its retain count by one and then you have to manually release it after its use is over.
Third Thing,
Whenever you add child your object it is retained automatically but you don't need to release it rather you remove it from the parent.

Do I have to set a removeEventListener when I called addEventListener?

I'm a beginner of ActionScript 3. Recently I'm trying to use addEventListener to invoke function. I found that there are some examples add a removeEventListener when they invoke functions, such as:
public function Away3DMultiMarkerDemo()
{
addEventListener(Event.INIT, initIN2AR);
super();
}
private function initIN2AR(e:Event = null):void
{
removeEventListener(Event.INIT, initIN2AR);
in2arLib.init( workW, workH, maxPoints, maxReferences, 100, stage );
in2arLib.setupIndexing(12, 10, true);
in2arLib.setUseLSHDictionary(true);
in2arLib.addReferenceObject( ByteArray( new DefinitionaData0 ) );
in2arLib.addReferenceObject( ByteArray( new DefinitionaData1 ) );
in2arLib.setMaxReferencesPerFrame(2);
in2arLib.setMatchThreshold(40);
intrinsic = in2arLib.getIntrinsicParams();
initCamera();
initAway3D();
initText();
initListeners();
}
My question is that do I need to set a removeEventListener each time when I called addEventListener? I did some research that the purpose of adding the removeEventListener is to release memory, otherwise program will keep listen events.
It is good practice to remove your listeners when you no longer need them. But that is a call you must make in each situation.
Adding an event listener by default will hang onto a reference of the thing it is added to. So if you add a listener to a movieclip, and delete that movieclip, it will not be garbage collected because the event listener still has a reference to it. For this reason it is good to remove any listeners on an object as part of your deletion process. Of course you can also use the "weak reference" argument in the addEventListener method, so the listener will not keep the garbage collector from destroying the object.
In the case of the Event.INIT event in your example; That should only ever fire once, so the event handler is the perfect place to make sure you remove the listener.
No. You only have to do this if you want the event to execute only once. You also call it when you no longer need the listener, so that it doesn't waste memory.
If you call it as the very first statement in the function that is called when the event is fired, it will ensure that the listener is only called once.

How much information should one pass through events?

Say, I have a datagrid with checkboxes, and each time a checkbox is marked I store the object in the data property of flex ResultEvent
public class MyItemRenderer extends ItemRenderer{
public static var CLICK:String = "CheckBoxClick";
protected function itemRendererClickListener(data:Object):void{
dispatchEvent(new ResultEvent(MyItemRenderer.CLICK, data))
}
}
I handle the result here.
protected function checkbox_clicked(event:ResultEvent):void{
//Here I do everything I want with the data.
Alert.show(event.result.toString());
}
This is what I've been using for months, but I never wondererd if this was a bad practice.
Or let alone bad practice, what is the optimal way to do this?
it's not really 'bad'. But it does create an additional reference to an object that can potentially keep that object in memory longer (or indefinitely if not managed well).
Generally speaking, you should only store data related to the event itself in the event instance. You can use the event.target and event.currentTarget properties to reference back to the object that dispatched the event and get data that way.
In your case, your event is a check box state change. The event itself (being checked) doesn't need any data associated with it besides the item being checked (which you can get with 'target' or 'currentTarget'). So it would be more appropriate in my opinion to do the following:
Alert.show(MyItemRenderer(event.currentTarget).data.toString());
This keeps your events more reusable
Best practice for Events with data is to use a custom event (see http://cookbooks.adobe.com/post_AS3__Creating_and_dispatching_Custom_Events-17609.html) for explanation
btw, another 'best practice' is to avoid the generic Object class in your code - instead, create a value object class