Why "saveobj" is invoked two times when saving a object?
4 ビュー (過去 30 日間)
古いコメントを表示
I defined a class that customs the save process.
% file ClassCustomSave.m
classdef ClassCustomSave < handle
%ClassCustomSave
properties
val
end
methods
function obj = ClassCustomSave()
%ClassCustomSave Constructor
end
function obj = saveobj(obj)
warning("val changed.");
obj.val = obj.val*2;
end
end
end
I run this main script.
clear;
o = ClassCustomSave();
o.val = 111;
save sv.mat
clear;
load sv.mat
o.val
I get 2 warnings and "o.val" is 444. How this happens?
0 件のコメント
回答 (1 件)
Matt J
2025 年 4 月 25 日
編集済み: Matt J
2025 年 4 月 27 日
I don't know why saveobj is called twice. Perhaps the first call is so save() can obtain a template of the object to be stored in the .mat file? In any case, even if saveobj were called only once, it would still be hazardous practice for you to use saveobj to edit and save the original object. Because of handle copy semantics, such changes would also be felt by the other copies of the object that remain in your workspace.
What you need to do, when saving handle objects is to move the property data to an unshared copy of the object. If you have R2024b+, you might find it helpful to use the newer framework with matlab.mixin.CustomElementSerialization. This automatically populates a serialization sObj with all the property data from your object. Since sObj is not handle-linked to the original instance(s) of obj, you can make modifications freely, without side effects:
classdef ClassCustomSave < handle & matlab.mixin.CustomElementSerialization
%ClassCustomSave
properties
val
end
methods (Static)
function modifyOutgoingSerializationContent(sObj,~)
warning('Val changing')
sObj.val = 2*sObj.val;
end
end
end
If we now run your test, you can see that the saving routine is still called twice, but the property modifications are not disturbed by the handle copy semantics.
o = ClassCustomSave();
o.val = 111;
save sv.mat
clear;
load sv.mat
o.val
3 件のコメント
Walter Roberson
2025 年 4 月 25 日
編集済み: Walter Roberson
2025 年 4 月 25 日
I do not understand how you were able to get that output in MATLAB Answers? Your classdef is in style "code example" and there is no attached .m file ClassCustomSave.m ? To run the code in Answers did you used to have an attached ClassCustomSave.m that you removed later after getting the output ?
Matt J
2025 年 4 月 25 日
To run the code in Answers did you used to have an attached ClassCustomSave.m that you removed later after getting the output ?
Yes, that is what I did.
参考
カテゴリ
Help Center および File Exchange で Java Package Integration についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!