MATLAB: Class GUI app CloseRequestFcn missing figure handles

classfiguregui

Consider this simple example:
classdef multi_gui
properties
fig1
fig2
end
methods
function obj = multi_gui()
obj.fig1 = figure('CloseRequestFcn', @obj.closeApp);
obj.fig2 = figure('CloseRequestFcn', @obj.closeApp);
end
function closeApp(obj, hObject, eventdata)
delete(obj.fig1)
delete(obj.fig2)
end
end
end
It's an app with 2 figures and when one is closed, the other is supposed to be closed as well. However, something is seriously going wrong in the CloseReqeustFcn callback. Using the debugger, I can see that fig1 and fig2 in obj in the callback are "unset", and therefore cannot be closed. What's going on here?

Best Answer

Solved it myself eventually.. apparently, the state of the "obj" is saved at the point when the callback is set, so when setting the callback of fig2, fig2 is not yet set in obj. similarly, when setting the callback of fig1, neither fig1 or fig2 exist in obj yet. so the solution looks like this.
function obj = multi_gui()
obj.fig1 = figure();
obj.fig2 = figure();
obj.fig1.CloseRequestFcn = @obj.closeApp;
obj.fig2.CloseRequestFcn = @obj.closeApp;
end
PS: more detailed explanation of the problem and "cleaner" ways of solving this are welcome.