Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an Objective-C property setter signal failure?

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 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?

like image 663
big_m Avatar asked Mar 31 '11 19:03

big_m


2 Answers

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.

like image 69
CRD Avatar answered Oct 19 '22 12:10

CRD


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.

like image 31
Ole Begemann Avatar answered Oct 19 '22 12:10

Ole Begemann