Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not is it a good practice to use self in initializer method in Objective-C? [duplicate]

I am aware that using setters in dealloc can create problems, if any other object is observing for changes in a property. But why should not we use them in initializers?

like image 877
RK- Avatar asked Feb 24 '12 12:02

RK-


2 Answers

I have never had any problems using accessors in initializers. Maybe it depends on how much magic you have in the setters and getters – if the accessors did something too smart, you might run into trouble when using them in the initializer.

Now that I think of it, I even use the accessors in dealloc. Again, without problems. If someone is observing an object, he should make sure that the object does not get deallocated in the first place.

So, unless somebody else comes up with a compelling counter-argument, I think you might try using the accessors both in init and dealloc and see how that works for you.

like image 114
zoul Avatar answered Oct 25 '22 22:10

zoul


The only reason not to use accessors in -init is because your object is not fully initialised and the accessor may depend on it. This is only likely to happen if you have a subclass that overrides the accessor methods.

There is a symmetrical problem on deallocation in that an overridden accessor might depend on not being called on a partially deallocated object. There is also the issue that you might send out spurious KVO notifications.

This goes to the heart of proper encapsulation. Subclasses should not need to care about the implementation details of the super class.

like image 41
JeremyP Avatar answered Oct 25 '22 21:10

JeremyP