Physics logo
Lancaster University Homepage
You are here:  SPP / Software / Sharing UserData

The UserData property is an area where user functions and callbacks can store and exchange internal state information. Using UserData is a much better approach than using global variables. If a function or callback is implemented using global variables then only one instance of that function/callback can be active at any time. For example, if a zoom function was implemented using global variables then zooming would work on only one axis at once, attempting to have more than one axis zoomed at any one time would cause confusion as there would be only one global variable in which to store the original axes limits. UserData provides a method to avoid this problem.

In a sophisticated GUI it will be found that multiple functions and callbacks will need to share access to UserData in a mutually-acceptable way. This can be achieved by only assigning structs to UserData, with each function/callback using its own field inside that structure. (There is still a possibility of name clashes but if the field names are based on the function names then the problem can be minimised.)

It is important to note that Matlab functions are interrupted by callbacks, and that callbacks can be interrupted by later callbacks. This is a dangerous situation when sharing UserData since the interrupting callback may modify the UserData. The interrupted callback would be unaware of the changes, saving back incorrect data. To prevent this happening it is necessary to set the Interruptible property to 'off' on any callbacks which access UserData. (Even read access is affected; the interrupting callback might read the original data values before the interrupted callback has saved the modified values, which could lead to the appearance that the second callback executed before the first, even though it was initiated afterwards!)

By default UserData is created as an empty double matrix. However, it is important that the initial UserData value is fetched from an object, even if just created by that function or callback. This allows other functions/callbacks the opportunity to set UserData with the Default... or CreateFcn properties.

The guidelines for sharing UserData are summarised below:

  1. When setting callbacks set the Interruptible property to 'off'.
  2. Every time the function/callback is executed fetch the UserData value, even if the GUI object has only just been created.
  3. Treat the UserData value as a struct (signal an error if it isn't empty and and isn't a struct). Choose a meaningful name for the field in that structure (preferably based on the function name) and store all data in that field (itself being a struct, if necessary).
  4. Update the UserData value after use.
  5. If making calls to functions which may change UserData save the value first, and reread UserData afterwards.

A Lancaster University approved page by Steve Marple.
© Lancaster University.