[MonoTouch] Handling exceptions in ViewDidLoad for modal views (tip)

competent_tech xamarinforums at competent.com
Tue Oct 25 14:36:49 EDT 2011


If you are showing a view modally and an exception occurs in the ViewDidLoad
override, you will not be able to open the view again. This can be a
significant time burner during development and could affect your users at
runtime if there is a transient error (out of memory, network connectivity
issues, etc).

I tried several solutions to this, including catching the exception in
ViewDidLoad and calling DismissModalViewControllerAnimated, but the view was
never unloaded from the root viewcontroller's ModalViewController.

After trying different approaches, I finally discovered that if I put the
DismissMVCA method call in ViewDidAppear, the view will be correctly
dismissed and can be opened again. 

The general approach is to catch the exception in ViewDidLoad, report the
exception to the user (optional), set a private member variable to indicate
that an exception occurred and in ViewDidAppear, if the private member
variable is set, Dismiss the view.

Because I didn't want to have to add this code to every modal view, I
created a base class that implements this behavior and is inherited by the
appropriate views. In order to enforce this behavior, I sealed the
ViewDidLoad and ViewDidAppear methods and provided overridable OnViewDidLoad
and OnViewDidAppear methods that inheritors use to perform there appropriate
actions. 

In order to limit the possibility for recursion by the inheritor calling
base.ViewDidXXX from the OnViewDidXXX methods, I marked the sealed methods
in the base class as obsolete. This generates a spurious warning in the base
class, which can be ignored, but will also catch any incorrect calls in
inheritors.

Hopefully this will help someone that has battled the same issue.

--
View this message in context: http://monotouch.2284126.n4.nabble.com/Handling-exceptions-in-ViewDidLoad-for-modal-views-tip-tp3937762p3937762.html
Sent from the MonoTouch mailing list archive at Nabble.com.


More information about the MonoTouch mailing list