MATLAB: Do I get warning messages when I have an event listener in the class and I execute the command: CLEAR CLASSES in MATLAB 7.6 (R2008a)

addlistenerclassevent listenerMATLABmcosoop

When I execute the following command in MATLAB:
clear classes
I get the following warning messages:
Warning: Objects of 'User1' class exist. Cannot clear this class or any of its super-classes.
Warning: Objects of 'enum_deb' class exist. Cannot clear this class or any of its super-classes.
This happens after I create the object like so:
t = User1
and I
when I define the two classes like so:
User1.m:
classdef User1 < handle
properties
a=enum_deb;
end
methods
function obj = User1()
lh = addlistener(...
obj.a,'updated',...
@(src,event)lstnrCallback(obj,src,event));
function lstnrCallback(obj,src,event)
disp('Listener Called');
end
end
end
end
enum_deb.m:
classdef enum_deb < handle
properties
index = 0;
end
events
updated
end
end

Best Answer

This is an expected behavior in MATLAB 7.6 (R2008a). What happens here is that the property intializer creates a single handle object that is shared by all instances. For example, defining the following class:
classdef sample
properties
rand_no = rand
end
end
and then creating 2 objects of the sample class like so:
A = sample
B = sample
results in both A and B having the same constant number for each of their rand_no property.
In the example case, the constructor attaches a listener to that single shared handle that is owned by the class definition. In addition, ADDLISTENER adds a hidden property to the object being listened to which therefore creates a circular dependency to the hidden handle. Thus, calling CLEAR CLASSES does not work properly and MATLAB has to be shut down to clear the hidden handle.
To work around this issue, create the enum_deb object in the constructor function instead of in the properties section. For example, create User1.m like so:
classdef User1 < handle
properties
a;
end
methods
function obj = User1()
obj.a = enum_deb; %(TechSup) create enum_deb object here instead
lh = addlistener(...
obj.a,'updated',...
@(src,event)lstnrCallback(obj,src,event));
function lstnrCallback(obj,src,event)
disp('Listener Called');
end
end
end
end
Additional useful information:
The difference between calling ADDLISTENER and EVENT.LISTENER is the following:
- ADDLISTENER automatically adds a hidden property to the object being listened to in order for the listener object to be bound to its lifecycle. This means that the listener object is destroyed once the object it is listening to is cleared from memory.
- On the other hand, the listener object created by EVENT.LISTENER is a local object. This means that deleting the object being listened to will NOT necessarily result in the destruction of the listener object as well.