An old post explains pretty well: Why shoudn't I use accessor methods in init methods
But my question is:
Q. If I am not overriding accessor methods in sub class in Objective C, is it safe to use in init
?
An old post explains pretty well: Why shoudn't I use accessor methods in init methods
But my question is:
Q. If I am not overriding accessor methods in sub class in Objective C, is it safe to use in init
?
Best practices from Apple say don't use self. accessors when in init or dealloc methods. It'll probably be fine, but basically Apple can't guarantee it.
It is usually avoided to prevent KVO mechanisms from accessing a partially initialised or partially deallocated object. This is particularly true for Mac OS X development where bindings and KVO play a large part especially in an application's user interface. I'm not an iPhone developer but if KVO is used on the iPhone platform as well, then it may be reason enough to avoid using accessor methods in your init
and dealloc
methods.
KVO makes a dynamic subclass of your class so that it can easily monitor changes to properties.
It's easy enough to avoid them in init
and dealloc
. Some argue that it's easier to use the accessor methods everywhere regardless of Apple's recommendations, but the convention is to avoid using them for init
and dealloc
and following the convention usually means less hurt later even if you don't anticipate any problems now.
If I am not overriding accessor methods in sub class in Objective C, is it safe to use?
Answer: Never user self.accessor.
From my 2+ years working experience under 20+ years apple developers(cocoa,obj-c), what I learnt is same.
Many a times our team has been asked to remove all those and and guided to use some other design pattern or way, even though it was required.
This may put you under problem if the object was created as nonatomic
, and many threads working on same property/object. self.
makes your class/object bind-ed. As you have tagged ios, for previous versions of ios this could have been done, but now ios are supporing kvo, so you should not follow this way.