MATLAB Answers

classdef delete function and figure CloseRequestFcn mixing problem

6 views (last 30 days)
Alessandro on 6 Mar 2013
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
%constructor generates a new figure
function obj = testclass()
obj.thefig = figure('CloseRequestFcn',@(src,evt) (disp('not allowed')));
%when I use clear the destructor isn t called anymore ?!?
function delete(obj)
disp('closing figure');
if ishandle(obj.thefig)
And then I do the following:
a = testclass
clear a
And here the class destructor didn t get called. What did I do wrong ?
per isakson
per isakson on 6 Mar 2013
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.

Sign in to comment.

Answers (1)

per isakson
per isakson on 6 Mar 2013
Edited: per isakson on 6 Mar 2013
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. [...]
clear name1 name2 name3 ... removes name1, name2, and name3 from the workspace.
[...]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 )

Community Treasure Hunt

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

Start Hunting!