Can I 'initialize' a handle object in such a way that isvalid(object) would return false?
6 views (last 30 days)
Show older comments
I'm trying to initialize a variable (MyHandle) that I want to be a handle pointing to some object but which can't currently be assigned to said object. I have code that needs to behave differently depending on if MyHandle is assigned or not yet and I haven't found a good way to test if MyHandle has been assigned to a valid object or not.
The function 'isvalid' seems like the right choice to test this, however, isvalid throws the error "Incorrect number or types of inputs or outputs for function isvalid." when run on MyHandle in its unassigned state. I've tried different ways to initialize it like "handle([])" and "[]", but they all return that same error.
I've found some bandaid solutions like initializing MyHandle to an instance of some arbitrary handle subclass and then deleting that initialized object, or assigning MyHandle to be a value of type double and then using "isnumeric" as my test function instead of "isvalid," but I was wondering if there is a more "correct" way to do it for the sake of best practices.
Below is a sample class that recreates the behavior described above. To restate my question in terms of the class below: Is there an initialization for MyHandle I can use in the properties block that will allow IsHandleAssigned to return false before the first time AssignHandle is run with a valid handle and return true afterwards? OR is there a different function besides isvalid that I should be using in IsHandleAssigned to achieve that behavior?
classdef ExampleClass < handle
properties
MyHandle %Will be a handle pointing to an object of an arbitrary class
% MyHandle = handle([]) < This initialization returns an error
% MyHandle = [] < This initialization returns an error
% MyHandle = 0 < This works if I replace 'isvalid' with 'isnumeric'
% but that seems like poor practice to do since it obfuscates the
% purpose of MyHandle
end
methods
function obj = AssignHandle(obj,handleIn)
%This method assigns the handle of whatever class it happens to
%be to my property.
obj.MyHandle = handleIn;
end
function HandleIsAssigned = IsHandleAssigned(obj)
%This method tests whether or not my handle was assigned. Is
%there a better function than isvalid to use?
HandleIsAssigned = isvalid(obj.MyHandle);
end
end
end
0 Comments
Accepted Answer
Matt J
on 30 Aug 2024
Edited: Matt J
on 30 Aug 2024
One way:
classdef ExampleClass < handle
properties
MyHandle
end
methods
function obj = AssignHandle(obj,handleIn)
obj.MyHandle = handleIn;
end
function HandleIsAssigned = IsHandleAssigned(obj)
HandleIsAssigned = isa(obj.MyHandle,'handle') && isvalid(obj.MyHandle);
end
end
end
More Answers (0)
See Also
Categories
Find more on Data Type Identification 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!