Why does a listener object, created with the addlistener function, still exist after the deletion of its source event?
13 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2020-8-11
回答: MathWorks Support Team
2020-8-11
"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
2020-8-11
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Develop uifigure-Based Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!