iOS: Prevent library from crashing entire app
I've written a library for iOS that is referenced via a single .h file (MyAdaptedViewController.开发者_如何学Goh).
This is essentially a view that sits inside a full UIViewController.
However due to the nature of the library, it may crash (dealing with signal processing, network connectivity and audio input/output).
What I would like would be for the entire app be protected from crashing if a crash occurs in the single UIViewController, i.e. if a crash occured, the user could continue using the app while MyAdaptedViewController was disabled. I understand that this will depend on the type of crash, but I was hoping most crashes / exceptions could be caught?
E.g.
would @try{}@catch{} or
void uncaughtExceptionHandler(NSException *exception)
be possible solutions?
NO! Catching exceptions in an iOS app is a exception to normal Cocoa coding conventions.
NSException
is for exceptional errors that you can not be expected to recover from at run-time.
NSError
is for errors you are excepted to recover from, or at least show the user, at run-time.
Do not try to handle every error that can be raised by catching exceptions. The APIs that Apple provide will only raise exceptions if you have done a programming error. For example if you try to access an object index out of bounds in an array, this is a programming error since you should have gotten your index correct before accessing the object.
For all other cases you should use instances of NSError
, just as Apple do.
If it is proper to do so handle the error in your lib internally. If not possible pass the error up to your caller, and let them handle it.
I have written a longer blog post on the topic here: http://blog.jayway.com/2010/10/13/exceptions-and-errors-on-ios/
精彩评论