MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

1

classdef delete function and figure CloseRequestFcn mixing problem

Alessandro さんによって質問されました 2013 年 3 月 6 日
Hello I was trying to build some special class that administrate a figure. I wannt that the figure gets closed only if the class object get deleted ! I have tryed the following :
classdef testclass < handle
properties
thefig
end
methods
%constructor generates a new figure
function obj = testclass()
obj.thefig = figure('CloseRequestFcn',@(src,evt) (disp('not allowed')));
end
%when I use clear the destructor isn t called anymore ?!?
function delete(obj)
disp('closing figure');
if ishandle(obj.thefig)
delete(obj.thefig)
end
end
end
end
And then I do the following:
a = testclass
clear a
And here the class destructor didn t get called. What did I do wrong ?

  3 件のコメント

Setting the CloseRequestFcn callback does not prevent the figure from being closed. You may want to consider setting CloseRequestFcn to delete the object.
I have sometime many figures open, and the simple closing of the figure makes the class object illegal. But you are right I still could close the figure over delete(gcf)
You can wrap handle graphic object in handle classes and make it work according to your original intention. The key is to keep 100% control over the references to your instances of the wrappers.

サインイン to comment.

1 件の回答

回答者: per isakson
2013 年 3 月 6 日
編集済み: per isakson
2013 年 3 月 6 日

Two figures are created in the constructor. The first value of obj.thefig is overwritten. I guess, you already found out that with only the first figure the class behaves as you expect. Comment out the second call to figure to verify.
The problem is with the anonymous function
@(src,evt) (disp('not allowed'))
Documentation says:
Object Scope and Anonymous Functions
Anonymous functions take a snapshot of the argument values when you define the
function handle. You must, therefore, consider this scoping when assigning the
Callback property. [...]
and
clear name1 name2 name3 ... removes name1, name2, and name3 from the workspace.
and
[...]MATLAB calls the delete method of any handle object (if it exists) when
the object is destroyed. h is a scalar handle object.[...]
Thus, (it is a bit tricky to find all the relevant information) the method delete is called when the last handle (/reference) to the object is destroyed. The reason the method is not called in your example is that there is still a reference to the object in the anonymous function, which is attached to the figure.
To make the class behave as you expect, change the value of CloseRequestFcn of the figure:
obj.thefig = figure( 'CloseRequestFcn', 'disp(''not allowed'')' );
To remove the figure and the object from memory by brute force:
delete( gcf )

  0 件のコメント

サインイン to comment.



Translated by