Suppose you have a property with copy semantics. What should you do in the setter if the copy method fails? (I presume this is a possibility, since a copy usually starts with an alloc/init combo, which can fail and return nil.) Apple recommends开发者_如何学C returning error codes rather than using exceptions, but a setter generally has a void return type. What is the recommended approach? How do you signal that an error has occurred?
The Apple recommendation is really that exceptions should be reserved for exceptional situations. This is sometimes a recommended programming practice anyway, but in the case of Objective-C is reinforced due to the higher cost of exception handling.
So you can throw an exception if you wish and it is appropriate, e.g. running out of memory (copy failed) is (hopefully!) exceptional.
That said, some programming practices also recommend that properties should not throw exceptions; usually on the basis that something that looks like assignment obj.property = value;
would be confusing if exceptions were thrown (unlike [obj setProperty:value]
).
So that get us to setting the property to the "zero" for the type (nil
, 0
, 0.0
, NO
etc.).
To return more details of the error record details of the error which can be queried after the "zero" has been detected. This is essentially the approach used by the underlying ("Unix") syscalls, and many library functions, were errno
is set before a "zero" is returned.
There is no way to signal an error, other than that the property whose setter you called would be nil
. You can check for nil
after executing the setter, just as you would to confirm success after alloc/init'ing a new instance.
精彩评论