Why is UserData preferred over guidata
8 views (last 30 days)
Show older comments
Storing app data in the UserData property of the main app figure is recommended over using guidata, because it can result in more readable code. For more information about storing and sharing app data, see Share Data Among Callbacks.
I do not understand why UserData results in more readable code. For example, extracting data from the UI in a callback is with guidata:
data = guidata(gobject);
and with UserData:
data = ancestor(gobject, "figure", "toplevel").UserData
What are the benefits of UserData over guidata and does it matter which one you use?
0 Comments
Accepted Answer
atharva
on 7 Dec 2023
Hey Guido,
I understand that you want to know what are the benefits of UserData over guidata.
UserData is a property that all graphics objects in MATLAB possess, and can be used to store any single, user-defined array with a particular object. While you cannot access an application data unless you know its name, any user-defined data (if it exists) can always be accessed using 'UserData' property with SET and GET methods.
h = surf(peaks);
set(h,'UserData',rand(5));
ud = get(h,'UserData');
GUIDATA is a function used to associate data with the figure containing the GUI. GUIDATA can manage only one variable at a time and hence the variable is usually defined to be a structure with mutliple fields. GUIDATA is commonly used to share handles to different sub-components of the GUI between the various callbacks in the GUI. GUIDE uses GUIDATA similarly to store and maintain the handles structure.
Internally, GUIDATA actually uses a particular entry in the application data to store the information. This can be seen by viewing the contents of GUIDATA:
edit guidata
---------------------------guidata.m----------------------------
% choose a unique name for our application data property.
% This file should be the only place using it.
PROP_NAME = 'UsedByGUIData_m';
% ...SNIP...
if nargin == 1 % GET
data = getappdata(fig, PROP_NAME);
else % (nargin == 2) SET
setappdata(fig, PROP_NAME, data_in);
end
In general, GUIDATA should be used to store and access information from the 'handles' structure, especially in GUIDE-generated GUIs. Saving large amounts of data in the 'handles' structure can sometimes cause a considerable slowdown, especially if GUIDATA is often called within the various sub-functions of the GUI.
I hope this helps!
0 Comments
More Answers (0)
See Also
Categories
Find more on Migrate GUIDE Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!