Why "saveobj" is invoked two times when saving a object?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Matt J
am 25 Apr. 2025
Bearbeitet: Matt J
am 27 Apr. 2025
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 Kommentare
Walter Roberson
am 25 Apr. 2025
Bearbeitet: Walter Roberson
am 25 Apr. 2025
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
am 25 Apr. 2025
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.
Siehe auch
Kategorien
Mehr zu Java Package Integration finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!