問題描述
一個(gè)簡單的問題.
如果我有一個(gè)屬性和一個(gè)用相同名稱聲明的 ivar:
if I have a property and an ivar declared with the same name:
在 .h 文件中:
(Reminder*)reminder;
@property(nonatomic,strong)(Reminder*)reminder;
在 .m 文件中,如果我使用 ARC,我應(yīng)該使用 ivar 還是 init 方法中的屬性?
in the .m file, should I use the ivar or the property in the init method if I'm using ARC?
- (id)initWithReminder:(Reminder*)reminder_ {
self = [super init];
if (self) {
reminder = reminder_;
}
return self;
}
或者我應(yīng)該像這樣使用該屬性來獲得自動(dòng)引用計(jì)數(shù)的好處:
Or should I use the property to get the benefit of the automatic reference counting like this:
- (id)initWithReminder:(Reminder*)reminder_ {
self = [super init];
if (self) {
self.reminder = reminder_;
}
return self;
}
我不確定在對象初始化的哪個(gè)時(shí)間點(diǎn)可以使用點(diǎn)符號(hào)訪問屬性.
I'm not sure at which point in the object's initialization the properties become accessible with the dot notation.
推薦答案
在部分構(gòu)造的狀態(tài)下使用直接訪問,不管 ARC:
Use direct access in partially constructed states, regardless of ARC:
- (id)initWithReminder:(Reminder*)reminder_ {
self = [super init];
if (self) {
reminder = reminder_;
// OR
reminder = [reminder_ retain];
}
return self;
}
這是因?yàn)?self.whatever
會(huì)觸發(fā)其他副作用,例如 Key-Value Observing (KVO) 通知,或者您的類實(shí)現(xiàn)(顯式)或子類覆蓋 setWhatever:
——這可能會(huì)將你部分初始化的實(shí)例暴露給其他 API(包括它自己的),這些 API 正確地假設(shè)它們正在處理一個(gè)完全構(gòu)造的對象.
This is because self.whatever
will trigger other side effects, such as Key-Value Observing (KVO) notifications, or maybe your class implements (explicitly) or a subclass overrides setWhatever:
-- and that could expose your partially initialized instance to other APIs (including its own), which rightly assume they are dealing with a fully constructed object.
您可以手動(dòng)驗(yàn)證一個(gè)類是否能夠在部分初始化的狀態(tài)下運(yùn)行,但這需要大量維護(hù)并且(坦率地說)當(dāng)其他人想要繼承您的類時(shí)是不切實(shí)際或不可能的.它需要大量的時(shí)間和維護(hù),這樣做并沒有實(shí)質(zhì)性的好處,尤其是如果您嘗試將這種方法用作慣例.
You could manually verify that a class is capable of operating in a partially initialized state, but that requires a lot maintenance and is (frankly) impractical or impossible when other people want to subclass your class. It requires a lot of time and maintenance, and there isn't substantiative benefit doing so, especially if you try to use the approach as a convention.
所以保證正確性的統(tǒng)一方式是在部分構(gòu)造狀態(tài)下使用直接訪問,避免使用訪問器.
So the uniform manner which guarantees correctness is to use direct access in partially constructed states, and avoid using the accessors.
注意:我使用的是部分構(gòu)造",因?yàn)槌跏蓟皇菆D片的一半;-dealloc
有類似的注意事項(xiàng).
Note: I am using "partially constructed" because initialization is only half of the picture; -dealloc
has similar caveats.
關(guān)于為什么應(yīng)該在部分構(gòu)造狀態(tài) (ARC || MRC) 中使用直接訪問的更多詳細(xì)信息可以在此處找到:初始化屬性,點(diǎn)表示法
Some more detail as to why you should use direct access in partially constructed states (ARC || MRC) can be found here: Initializing a property, dot notation
這篇關(guān)于我應(yīng)該在 ARC 的 init 方法中引用 self.property 嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!