Saving and Loading Dynamic Properties

Reconstructing Objects That Have Dynamic Properties

If you use the addprop method to add dynamic properties to a MATLAB® class derived from the dynamicprops class, those dynamic properties are saved along with the object to which they are attached when you save the object to a MAT-file. See Dynamic Properties — Adding Properties to an Instance for more information about dynamic properties.

Why You Need saveobj and loadobj Methods

save saves dynamic properties and their values. However, save does not save dynamic property attributes because these attributes are not specified in the class definition. If you are saving an object that has dynamic properties, and these properties use nondefault attributes, you need to manage the saving and loading of attribute values using saveobj and loadobj.

If your class implements a saveobj method that converts the object to another type of MATLAB variable, such as a struct, you can save the dynamic property's attribute values so that your loadobj method can reconstruct these properties. The attribute values of dynamic properties are not part of the class definition and might have been set after the properties were attached to the object, so these values might not be known to the loadobj method.

Implementing the saveobj and loadobj Methods

For example, your saveobj method can obtain the nondefault attribute values from the dynamic property's meta.DynamicProperty. Suppose the object you are saving has a dynamic property called DynoProp, and your saveobj method creates a struct s to save the data that the loadobj method uses to reconstruct the object:

   function s = saveobj(obj)
   % Obtain the meta.DynamicProperty object for the dynamic property
   metaDynoProp = findprop(obj,'DynoProp');
   % Record name and value for the dynamic property
   s.dynamicprops(1).name = metaDynoProp.Name;
   s.dynamicprops(1).value = obj.DynoProp;
   % Record additional dynamic property attributes so they can be
   % restored at load time, for example SetAccess and GetAccess
   s.dynamicprops(1).setAccess = metaDynoProp.SetAccess;
   s.dynamicprops(1).getAccess = metaDynoProp.GetAccess;

Your loadobj method can add the dynamic property and set the attribute values:

methods (Static)
   function obj = loadobj(s)
   % first, create an instance of the class
      obj = ClassConstructor;
      % Add new dynamic property to object
      metaDynoProp = addprop(obj,s.dynamicprops(1).name);
      obj.(s.dynamicprops(1).name) = s.dynamicprops(1).value;
      % Restore dynamic property attributes
      metaDynoProp.SetAccess = s.dynamicprops(1).setAccess;
      metaDynoProp.GetAccess = s.dynamicprops(1).getAccess;
Was this topic helpful?