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

조회 수: 2 (최근 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
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개)

카테고리

Help CenterFile Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by