Why does a listener object, created with the addlistener function, still exist after the deletion of its source event?

13 次查看(过去 30 天)
According to the documentation on the listener lifecycle here:
"When the event source object is destroyed, MATLAB® automatically destroys the listener object."
However, running the following code shows that the listener object 'v' still exists after the deletion of its source event, i. e. the figure 'f':
>> f = uifigure();
>> v = addlistener(f, 'ObjectBeingDestroyed', @(src, event) disp('ja'))
>> delete(f);
>> v
This issue has been discussed on MATLAB Answers, see link: https://www.mathworks.com/matlabcentral/answers/510296-listener-object-not-destroyed .
This behaviour seems to be contrary to the documentation. What is the expected behaviour?

采纳的回答

MathWorks Support Team
The addlistener function allows code to attach a listener to one or more sources so that the listener will be referenced by the source object(s) and stay around at least as long as any of the source object(s) stays around provided the listener is not explicitly destroyed. When the source object(s) is/are destroyed, the listener will be automatically destroyed if there is no other variable holding onto the listener. In the example code provided, the simplest way to make sure that the listener is destroyed when the source is destroyed is to not assign the output variable 'v':
>> f = uifigure();
>> addlistener(f, 'ObjectBeingDestroyed', @(src, event) disp('ja'))
>> delete(f);
In the code example in the question, the variable 'v' is holding onto the listener, which prevents it from being deleted. Thus, this is expected behaviour.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Develop uifigure-Based Apps 的更多信息

标签

尚未输入任何标签。

产品


版本

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by