Clarifications regarding weak references in actionscript listeners

后端 未结 1 619
挽巷
挽巷 2021-01-24 08:54

I understand how weak references work, but I am bit confused regarding it\'s use in actionscript event listeners. Consider the example below:

public class Rectan         


        
相关标签:
1条回答
  • 2021-01-24 09:18

    The basic rule for garbage collection in Flash is that if an object is referenced (directly or indirectly) from the timeline, it cannot be garbage collected. This means that if an instance of your class is not being referenced from anywhere in the root display list (or by an object that is in turn referenced from the root, et c recursively), it will be collected regardless of whether it has references to itself.

    This also means that two objects that reference each other, but are not being referenced in any way from the root display list, should be eligible for garbage collection.

    The weak reference option in event listeners is mainly so that you won't have to remove the event listener manually. I personally tend not to use it, because I like to have full control of when objects get marked for garbage collection.

    So, in your first example, the Foo instance is in all cases eligible for garbage collection. In your second, whether or not the Rectangle instance can be garbage collected depends on whether it's referenced from the display list. The useWeakReference flag in this regard makes no difference.

    From the documentation here:

    Class-level member functions are not subject to garbage collection, so you can set useWeakReference to true for class-level member functions without subjecting them to garbage collection. If you set useWeakReference to true for a listener that is a nested inner function, the function will be garbage-collected and no longer persistent. If you create references to the inner function (save it in another variable) then it is not garbage-collected and stays persistent.

    0 讨论(0)
提交回复
热议问题