簡體   English   中英

使用@synthesize自動iVars

[英]Automatic iVars with @synthesize

我知道從iOS 4開始,現在可以根本不聲明iVars,並允許編譯器在您合成屬性時自動為您創建它們。 但是,我找不到Apple關於此功能的任何文檔。

此外,是否有關於使用iVars和屬性的最佳實踐或Apple推薦指南的文檔? 我總是使用這樣的屬性:

.h文件

@interface myClass {
    NSIndexPath *_indexPath
}

@property(nonatomic, retain) NSIndexPath *indexPath

@end

.m文件

@implementation myClass

@synthesize indexPath = _indexPath;

- (void)dealloc {
    [_indexPath release];
}
@end

我使用_indexPath而不是indexPath作為我的iVar名稱,以確保在需要使用indexPath時我不會使用self.indexPath 但是現在iOS支持自動屬性,我不需要擔心。 但是,如果我省略了iVar聲明,我應該如何處理在dealloc中釋放它? 我被教導在dealloc中釋放時直接使用iVars,而不是使用屬性方法。 如果我在設計時沒有iVar,我可以直接調用屬性方法嗎?

我經歷了很多不同的處理方式。 我目前的方法是在dealloc中使用屬性訪問。 在我不知道的情況下(在我看來)不要做太多的設法,除非在我知道屬性有奇怪行為的情況下。

@interface Class
@property (nonatomic, retain) id prop;
@end

@implementation Class
@synthesize prop;

- (void)dealloc;
{
    self.prop = nil;
    //[prop release], prop=nil; works as well, even without doing an explicit iVar
    [super dealloc];
}
@end

相反,我做了以下事情:

@interface SomeViewController : UIViewController

@property (nonatomic, copy) NSString *someString;

@end

接着

@implementation SomeViewController

@synthesize someString;

- (void)dealloc
{
    [someString release], someString = nil;
    self.someString = nil; // Needed?

    [super dealloc];
}

@end

注意:在某些時候,Apple將啟用默認的合成,這將不再需要@synthesize指令。

您可以使用->符號而不是點直接訪問實例變量. (將調用ivar相應的訪問器方法):

。H

@interface myClass {
}
@property(nonatomic, retain) NSIndexPath *indexPath

@end

.M

@implementation myClass

- (void)dealloc {
    [self->indexPath release];
    self->indexPath = nil; // optional, if you need it

    [super dealloc];
}
@end

因此,您將直接訪問iVar而不是相應的訪問方法,從而獲得額外的好處 - 性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM