I’m looking to start putting error catches into my code, and I want to see what NSError objects do for me on their own and what I’d have to add in myself.
Looking at this SO question and the Apple Docs, it looks like all NSError does is hold onto a numeric error code, the location of the error, and a description of the error. For all three of these items, I have to specify them in my code. Then, if I want to do something like skip to the end of any methods currently being executed (that would most likely cause a crash if the app tried to run them), or display a UIAlertView telling the user there was an error, I have to specify all of that on my own as well, correct?
I’m a bit of a beginner, so is there anything else I would want to consider doing?
NSErroris a container for error information, it does not do anything on its own. The class is designed so that different parts of your code could communicate error information to each other in a standardized way. Simply setting an error inside a method that takesNSError**does nothing – it’s the responsibility of the caller to check if*erroris non-nil, skip to the end of the method, display localized description, prompt the user for an action, and so on.However,
NSErroris flexible enough to enable you to do all that: the caller can provide pretty much any kind of information; you can track recovery attempts, display localized messages to the user, or store additional information in theNSErrorobject, and return it further down the call chain.Note: Cocoa framework methods generally require that you check the direct return value before using the
NSError, not checking whether the error isnil. The error is guaranteed to be valid if the method indicates failure, but it is not guaranteed to benilfor success, even if you set it tonilbeforehand.