例如,我在iPhone項目的應用程序委託中看到過類似的代碼。@synthesize variable = _variable會做什麼?
什麼是下劃線的變量?我可以將它用作變量的setter和getter嗎?
也釋放變量時應該使用:
[variable release];
或
[_variable release];
感謝。
例如,我在iPhone項目的應用程序委託中看到過類似的代碼。@synthesize variable = _variable會做什麼?
什麼是下劃線的變量?我可以將它用作變量的setter和getter嗎?
也釋放變量時應該使用:
[variable release];
或
[_variable release];
感謝。
在一些編碼約定中,實例變量之前的下劃線用於能夠快速區分它們與其他變量。它還有助於避免與方法和子類方法中的局部變量發生命名衝突。
@synthesize variable = _variable
創建一個setter和getter來設置/獲取您在此例中設置的變量_variable。所以外部訪問使用像object.variable這樣的代碼,它真的只是返回_variable。然而這個類通常在內部使用_variable。
@synthesize variable = _variable;
屬性名稱爲「variable」,備份它的實例變量名爲「_variable」。您應該使用訪問器-variable
和-setVariable:
,而不是直接訪問伊娃,除非在-init和-dealloc中使用_variable
。
在您的示例變量是一個屬性和_variable是一個實例變量。爲了簡單起見,我們可以說通過合成你本質上是指示屬性(在我們的情況下是變量)將使用實例變量(在我們的例子中是_variable)來存儲和檢索值。你真正在做的是指示編譯器創建符合屬性聲明中給出的規範的實現。
當您使用屬性時,建議的釋放方式是將其分配爲零。這實質上會釋放對象,並將實例變量設置爲nil而不是懸掛指針。
如果你沒有使用屬性,那麼你可以調用實例變量的版本,然後理想情況下你想將它設置爲零。
[在Objective C中使用下劃線前綴屬性名稱](http://stackoverflow.com/questions/3521254/prefixing-property-names-with-an-underscore-in-objective-c)和[如何在變量工作前面的下劃線](http://stackoverflow.com/questions/822487/)和[下屬性名稱前綴](http://stackoverflow.com/questions/5582448/underscore-prefix- on-property-name)和[爲什麼你爲一個實例變量使用下劃線而不是它的相應屬性?](http://stackoverflow.com/questions/2371489/) –
沒有人提到要釋放哪個變量! – Samssom