Clear Filters
Clear Filters

Error "Invalid or deleted object." when close a GUI in App Designer

14 views (last 30 days)
Hi, I tried to create an app simply to display capture from a webcam. The main functions are like below.
properties (Access = private)
KeepRunning = 1;
cam = webcam('USB Video Device');
end
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.cam.Resolution = '640x480';
while 1
rgbImage = snapshot(app.cam);
imshow(rgbImage,'Parent',app.UIAxes);
drawnow;
end
end
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
delete(app.cam)
delete(app)
end
end
Everything works fine; however, as I close the GUI (using X button), this error popped up. Any ideas?
Invalid or deleted object.
Error in app_test/startupFcn (line 23)
rgbImage = snapshot(app.cam);
Error in app_test (line 84)
runStartupFcn(app, @startupFcn)

Accepted Answer

Guillaume
Guillaume on 3 Jul 2018
I'm not convinced of the wisdom of having a never ending loop in your startupFcn.
Anyway, the problem is simple when you close the app, your close request callback deletes app.cam making it an invalid handle. Your infinite loop in startupFcn is still running and tries to access the now deleted app.cam, hence the error.
The naive fix would be to change the
while 1
to
while isvalid(app.cam)
99% of the time, it'll fix the error. However, were the user to close the app just after the while has executed but before the snapshot line has executed, you'll still get the error. A foolproof way would be:
while true
try
rgbImage = snapshot(app.cam);
catch
%error occured, probably app.cam was deleted. Quit loop
break;
end
imshow(rgbImage,'Parent',app.UIAxes);
drawnow;
end
  3 Comments
Guillaume
Guillaume on 4 Jul 2018
Edited: Guillaume on 4 Jul 2018
I assume that this error is from the 'catch', right?
I don't think so. I don't know the App Designer enough to say for sure but I suspect that it's because you have that infinite loop in the startup function that you get this error. It's certainly nothing to do with the catch. The code that is causing the error looks like code that should run when the App window is created. However, since you only return from the startup function when the app is closed, that code only runs after the app is destroyed, by which point most objects no longer exist.
Yeah, I'm aware of this but don't know how to fix it
First thing that comes to mind is to use a timer at the same or slightly faster rate than the frame rate of your camera.
Trinh Nguyen
Trinh Nguyen on 4 Jul 2018
I fixed it. I created a public function which includes the view-capture code above. This would avoid the infinite loop in the startup function. Thank you for your help :D

Sign in to comment.

More Answers (0)

Categories

Find more on Develop uifigure-Based 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!