preventing access to MAT file while saveobj is working
1 view (last 30 days)
Show older comments
Here's one. In order to be able to save a deep object (class with properties that are classes themselves), I save all properties into a struct recursively, and add a new field to structs that represent deep objects with their name ("CLASSNAME"). Later when loading the class, I can reconstruct these objects and overwrite their properties.
Issue is, I have a property (dependent, but doesn't have to be) that checks if a MAT file exists. So when the saveobj() method is iterating over the properties, it gets the value of this property which tries to load the MAT file that's just being saved. I could start a list of "blacklisted" properties to not query while saving, but this means hard-coding property names, which is not very elegant. Is there a way to tell if a saveobj() is currently running, or some other elegant way to write this?
Here's a minimum example code:
classdef whilesaving
properties (Dependent, Transient)
itexists
end
methods
function saveme(obj)
save('mat','obj');
end
function tf = get.itexists(obj)
mat = matfile('mat');
tf = isfield(mat,'obj');
end
function s = saveobj(obj)
s = obj2struct(obj);
%%
function s = obj2struct(obj)
if ~exist('s','var'), s = struct(); end
mobj = metaclass(obj); % can't use "findprop()" with value classes
props = {mobj.PropertyList.Name};
for n = 1:numel(props)
p = props{n};
% ADD THIS TO FIX IT: if mobj.PropertyList(n).Transient, continue; end
v = obj.(p);
if ~isobject(v) || isenum(v)
s.(p) = v;
else
sn = obj2struct(v);
sn.CLASSNAME = class(v);
s.(p) = sn;
end
end
end
end
end
end
Just run:
whilesaving().saveme
And you shall receive:
Warning: While saving an object of class 'whilesaving':
Unable to read MAT-file mat.mat: not a binary MAT-file.
> In whilesaving/saveme (line 8)
Warning: While saving an object of class 'whilesaving':
Unable to read MAT-file mat.mat: not a binary MAT-file.
> In whilesaving/saveme (line 8)
UPDATE: Okay, so just after posting the question I got the idea to make the property "Transient" and then ignore it in obj2struct, see commented line in the code. But since I already posted: any suggetsions for a cleaner implementation? :)
0 Comments
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!