Storing classes as appdata and modifying them
이전 댓글 표시
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?
채택된 답변
추가 답변 (1개)
Sean de Wolski
2014년 7월 2일
1 개 추천
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.
카테고리
도움말 센터 및 File Exchange에서 Graphics Object Properties에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!