Don’t Use Accessor Methods in Initializer Methods and dealloc
I am doing some reading about the Memory Management and they not recommend to use accessor methods in initializer method.
Question : why should not we use accessor methods in initilizer method
I was searching coupe of references about this issue on stackoverflow and other sites as well. However, I am not still confusing about it.
Can anybody advice me on this issue or if you can throw at me an example or a good reference so that I can go thru it by myself. Thanks
Here's an example I wrote which demonstrates two things:
Initializing a property, dot notation
Although the example focuses on initialization, dealloc
is susceptible to similar categories of problems. As one specific example: an object may partially resurrect itself in dealloc
, and reference count imbalances become a potential danger.
Briefly, you want to focus on correct initialization and cleanup of the data your objects need -- rather than the behavioral concerns/influence of your objects through any subclasses.
More reading:
Why myInstance = nil instead of self.myInstance = nil?
Should I refer to self.property in the init method with ARC?
Best way to set a retained property to a newly created object
KVC observers monitor the getter and setter methods. Unless you are absolutely certain that no-one will ever observe your property, then you are asking for trouble. Have a defect where an observer is mucking around with a partially dealloc'ed object is very hard to reproduce and nearly impossible to test for.
That is a bit of a religious issue with developers on both sides and the arrival of ARC has further muddied the issue.
A couple of reasons are:
The object is not fully initialized and the accessor may depend on a fully initialized object.
The accessor may have side effects and again the object is not fully initialized. One common side effect is instantiating an iVar on first use.
These arguments can also apply to using accessors in dealloc
(for non-ARC code).
上一篇: 如何制作导航