Implementing saveobj and loadobj for classes with handle references

8 views (last 30 days)
I have two classes, handleClass is a handle class and valueClass is a value class. valueClass contains a property which refers to a handleClass object.
An array of HandleClass objects is kept which are referred to by an array of ValueClass objects, to ensure future compatibility there is a need to implement the saveobj and loadobj methods in both classes. However, when loading the saved data the ValueClass objects no longer refer to the objects in the HandleClass array but rather create a new object.
The loading behaviour is as expected if the saveobj and loadobj methods are not implemented which suggests that the behaviour I want is possible but I haven't been able to find any examples or documentation which explains how to do this.
In my code I can see I am calling HandleClass.saveobj() for the reference and I know its the wrong way to do it but I have no idea how to save and load the reference as a reference and not as a separate object.
  1 Comment
Adam
Adam on 19 Feb 2015
What do you expect it to be a reference to once it is saved? I haven't ever needed to write these functions myself yet and have just used default object saving, but I'm not sure I see how an object could save itself to file with a reference to some object that is in the workspace. When you load it back in the old workspace object will no longer exist so the loaded object cannot still contain a reference to it.

Sign in to comment.

Answers (1)

Matt J
Matt J on 19 Feb 2015
Edited: Matt J on 19 Feb 2015
You cannot preserve handle linking among object instances when you save the objects to a .mat file. However, once you have reloaded the ValueClass object array, let's call it arrayValue, it is very easy to create a separate array of its handle class members
arrayHandle = [arrayValue.handleprop];
In other words, there is no need to save the HandleClass object to the .mat file to begin with, in fact, it wastes disk space to do so. The .mat file just creates deep copies of all instances of the handle objects on disk.

Categories

Find more on Object Save and Load in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!