Storing classes as appdata and modifying them
Show older comments
Apologies if this has been asked before, I have not been able to find any similar questions on Matlab Central or any other site.
Say I have a variable, and I store this variable as AppData. If I go modify the variable after storing it as appdata, it will not change the appdata.
>> number = 0;
>> setappdata(0,'NumberStorage',number)
>> number = 10;
>> getappdata(0,'NumberStorage')
ans =
0
Say I have a class, defined as follows:
classdef SampleClass < dynamicprops
properties
testValue = 0;
end
end
If I create an instance of this class and store it as appdata and then modify it after the fact, it does change the appdata.
>> object = SampleClass;
>> object.testValue = 0;
>> setappdata(0,'ObjectStorage',object)
>> object.testValue = 10;
>> getappdata(0,'ObjectStorage')
ans =
SampleClass with properties:
testValue: 10
My question is, why does this happen? And how can I prevent it from happening?
Accepted Answer
More Answers (1)
Sean de Wolski
on 2 Jul 2014
1 vote
Since your class inherits from dynamicprops which inherits from handle, the thing being stored to appdata is a handle to the object. Thus any other handle to this same object will modify it.
To prevent it from happening, make your class a value class that does not inherit from dynamicprops or make a second instance of it by rerunning the constructor.
Categories
Find more on Graphics Object Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!