问题描述
我想使用ovveride getter进行延迟实例化,并保留默认的setter.
I want to ovveride getter for lazy instantiation and leave default setter.
我需要@synthesize吗?
Do I need @synthesize ?
为什么?
@interface Foo()
@property (strong, nonatomic) NSObject *bar;
@end
@implementation Foo
- (NSObject *)bar
{
if(!_bar) _bar = [[NSObject alloc] init];
return _bar;
}
@end
更新:我已经更改了变量和类名,因为这令人困惑.从Deck and Card到Foo and bar.
Update: I've changed variable and class name, because it was confusing. From Deck and card to Foo and bar.
推荐答案
否,如果您明确实现所有访问器方法(readwrite
的getter和setter),则只需显式地合成(以获取合成的ivar).属性,仅是readonly
属性的吸气剂).您已经为此readwrite
属性编写了getter方法,但没有编写setter方法,因此ivar仍将为您合成.因此,就您的代码而言,您无需显式地@synthesize
.
No, you only need to explicitly synthesize (to get the synthesized ivar) if you explicitly implement all of the accessor methods (both getter and setter for readwrite
properties, just the getter for readonly
properties). You've written the getter for this readwrite
property, but not the setter, so the ivar will still be synthesized for you. Thus, as your code stands, you do not need to explicitly @synthesize
.
如果将此属性设置为readonly
,则实现getter将阻止ivar自动合成.同样,由于这是readwrite
,因此,如果同时实现了getter和setter,则将需要综合ivar(如果需要).
If you made this property readonly
, then implementing a getter would prevent your ivar from being automatically synthesized. Likewise, since this is readwrite
, if you implemented both the getter and the setter, that would require you to synthesize the ivar (if you wanted one).
这篇关于覆盖getter只需要@synthesize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!