[英]Is it recommended to define ivars for readonly synthesized properties?
我發現很多時候我想擁有一個合成的只讀屬性,例如,我只是根據其他變量實現了該屬性的getter方法,而無需使用ivar( 注 :界面中的ivars,因為我使用的是OmniGraffle UML軟件,它無法識別由合成屬性自動生成的ivars):
@interface Editor : UIView {
BOOL _wordWrap;
BOOL _showLineNumbers;
NSDictionary *_options;
}
@property (nonatomic) BOOL wordWrap;
@property (nonatomic) BOOL showLineNumbers;
@property (nonatomic, copy, readonly) NSDictionary *options;
@end
@implementation Editor
@synthesize wordWrap = _wordWrap;
@synthesize showLineNumbers = _showLineNumbers;
@synthesize options = _options;
- (NSDictionary *)options {
return @{
@"WordWrap" : [NSNumber numberWithBool:self.wordWrap],
@"ShowLineNumbers" : [NSNumber numberWithBool:self.showLineNumbers],
};
}
@end
在上面的Editor
類中,是否有必要在標頭定義中定義_options
ivar, 更重要的是,自動生成的ivar是否占用符號表中的內存或空間? 另外,在這種情況下使用copy
, retain
或不使用值會更有效嗎? 只是好奇。
首先:停止將ivar聲明放在@interface
。 它們屬於您的@implementation
。 請參閱此答案以獲取詳細說明。
無論如何,鑒於您所寫的內容,您的@synthesize options = _options
無效。
@synthesize
具有兩個可能的效果:
如果您的類沒有一個實例變量,它將添加一個名為_options
的實例變量。
如果您的類沒有名為options
方法,它將生成一個getter方法options
,該方法返回_options
的值。
由於您手動定義了實例變量和getter,因此@synthesize
不執行任何操作。 您可以完全刪除它,而無需更改程序的含義。
在只讀屬性上指定copy
無效。 copy
和retain
(或更確切地說,在ARC下, strong
屬性)僅影響生成的setter方法,並且編譯器不會為readonly
屬性生成setter。 (如果將屬性更改為在類擴展中為readwrite
,則進行copy
。)
是的, _options
ivar占用了符號表中的內存(對於每個Editor
實例)和空間。 由於您沒有使用_options
ivar,因此應將其完全刪除。 您還應該完全刪除@synthesize
,以便編譯器不會為您生成_options
ivar。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.