以下討論在 MRC 下。
1,不要在init和dealloc函數中使用accessor
Don’t Use Accessor Methods in Initializer Methods and dealloc The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:
dealloc 實現:
不推薦:
-(void)dealloc { self.name = nil; [super dealloc] }
推薦:
-(void)dealloc {
[_name release]; _name = nil; [super dealloc] }
init 實現:
不推薦:
- init { self = [super init]; if (self) { self.count = [[NSNumber alloc] initWithInteger:0]; } return self; }
推薦:
- init { self = [super init]; if (self) { _count = [[NSNumber alloc] initWithInteger:0]; } return self; }
why: 對於init 中使用 self.name 訪問器會引發其他副作用,可能會對鍵-值觀察(KVO)的通知,或者你的子類 重載了 name的屬性訪問器(子類覆蓋了父類的實現。)
假如Custom 實現如下,有一個屬性count.
- init { self = [super init]; if (self) { self.count = [[NSNumber alloc] initWithInteger:0]; } return self; }
Custom 的子類是 CustomSub,且實現如下
- init { self = [super init]; if (self) { } return self; }
同時重寫了父類count 屬性訪問器
-(NSNumber *)count{ //custom.... }
-(void)setCount:(NSNumber *)number{ //custom..... }
當你在初始化子類
self = [super init]; 它會從NSObject ->Custom->CustomSub 中 調用init 分別初始化當前類得成員,你子類中重寫了Custom 屬性訪問器,那么就會影響Custom 初始化自己的 成員count .
這是從設計模式上來說,子類不應該去影響父類初始化自己的成員。這樣可能導致其他問題。
如果我們中規中矩的 這么寫,可能不會出現問題。那我要想使壞,那...你懂的。。
so 我們應該在init 或 dealloc 中使用_count 直接訪問屬性。則不會出現上述問題。
dealloc 中使用 self.count
----------有可能count的生命周期已經結束,不能再接受消息--------
上面是從其它文章中拷過來的,我沒太明白是在什么樣的情況下,按理說 對一個nil 對象發送releas 消息不會有問題。
我個人理解: 其實init 、dealloc 中不建議使用 訪問器而直接使用_property 根本原因是
子類不應該去影響 父類 初始化 和 釋放 自己資源(property)【通過上面可知子類覆蓋父類屬性訪問器的后果】,使用_property 可以有效避免一些未知錯誤。
http://fann.im/blog/2012/08/14/dont-use-accessor-methods-in-init-and-dealloc/
2, 為什么 [super dealloc]; 要在最后
-(void)dealloc { //custom release self source [super dealloc] }
釋放類的內存是在NSObject 里定義的,釋放順序應該是
先釋放我本類里的source , 在調用父類中的dealloc .應該本類中可能擁有不止一個父類,沿着繼承鏈
依次釋放父類中的資源。
這個過程和init 過程相反,
-(id)init{ self = [super init]; if(self){ //custom init } }
注:可以把init過程比作生成一個洋蔥,從最核心的NSObject(分配內存、初始化屬性。)
外層逐層初始化自己的東西,直到本類……
dealloc 同理可以比作 卜洋蔥。