What are best practices for error handling when writing an API for the iphone?

前端 未结 2 1044
说谎
说谎 2021-02-05 21:37

We are writing an API for iphone developers and we don\'t know what the best practice is for exception handling. We looked into NSError, standard POSIX way, N

2条回答
  •  忘了有多久
    2021-02-05 21:48

    +1 for NSError.

    I forget where in the Apple docs I read this, but I also recall them encouraging the coding philosophy of "try first, then check for errors," as opposed to "check for validity, then do the operation." For example, instead of seeing if the network is available before using it, just try to use it and respond to an error if/when you get one back.

    I agree with this philosophy for many use cases because (a) it moves validity-checking to the moment of action, so in a sense it's more accurate, and (b, subjective) it's more fun to work with code in this pattern.

    To summarize, the suggestion is to use NSError, and to provide immediate feedback with NSError** parameters that accept NULL, to be very friendly to your API-users! This pattern is also established in several places in Cocoa/Touch; for example the NSString method writeToFile:atomically:encoding:error:.

提交回复
热议问题