How to check if handle is to a deleted object?
Anonymous function to detect if a variable is a deleted object.
isDeletedObj = @(h)isobject(h) & ~isgraphics(h);
Note: Tests below show that this function will also identify graphics placeholders. To eliminate detection of graphics place holders,
isDeletedObj_2 = @(h)isobject(h) & ~isgraphics(h) & ~isa(h,'matlab.graphics.GraphicsPlaceholder');
To test for a specific type of deleted object, add a condition that tests the class of the input variable.
isDeletedAxes = @(h)isobject(h) & ~isgraphics(h) & isa(ax,'matlab.graphics.axis.Axes');
idx = isDeletedObj([fig, ax, h])
Comparison with other methods
Both versions of isDeletedObj() return true for deleted object handles; other functions return false.
All functions correctly return false for (most) non-graphics objects. Non-graphics inputs can occur when validating inputs to functions that contain optional parent handles as inputs. Since functions other than isDeletedObj and isDeletedObj_2 return false in this example and the example above, a false output does not mean that the input is a deleted object!
Both versions of isDeletedObj() correctly return false for existing object handles; other functions correctly return true.
Both versions of isDeletedObj() correctly return false for an integer that coincides with an existing figure number or matlab root number (0). All other tests fail to distinguish figure handles from their integer representation! This is because the Matlab functions support backward compatibility prior to the graphics changes in r2014b.
When testing graphics placeholders (gobjects), isDeletedObj() and isvalid() return true while isDeletedObj_2() returns false. This examples shows the only difference between the two versions isDeletedObj.
- A false output to Matlab's object validity tests (ishandle, ishghandle, isvalid, isgraphics) does not mean that the input is a deleted object.
- Matlab's object validity tests return true for an input 0 or any integer that corresponds to a an existing figure number.
- isDeletedObj only returns true when the input is a deleted object or object place holder (gobjects).
- isDeletedObj_2 only returns true when the input is a deleted object and returns false for obj place holders.