Storing classes as appdata and modifying them
Mostra commenti meno recenti
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?
Risposta accettata
Più risposte (1)
Sean de Wolski
il 2 Lug 2014
1 voto
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.
Categorie
Scopri di più su Graphics Object Properties in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!