是否建议为只读合成属性定义ivars?

时间:2014-07-09 20:24:17

标签: ios objective-c properties synthesize ivars

我发现很多时候我想要一个合成的只读属性,我只是根据其他变量实现该属性的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占用内存或符号表中的空格?此外,在这种情况下使用copyretain或没有值会更有效吗?好奇。

1 个答案:

答案 0 :(得分:4)

首先:停止将您的ivar声明放在@interface中。它们属于您的@implementation。有关详细说明,请参阅this answer

无论如何,鉴于你所写的内容,你的@synthesize options = _options无效。

@synthesize有两种可能的影响:

  1. 如果您的班级没有名称_options,则会添加一个名为options的实例变量。

  2. 如果您的类没有名为_options的方法,则会生成一个getter方法options,该方法返回@synthesize的值。

    < / LI>

    由于您手动定义了实例变量和getter,因此copy不执行任何操作。您可以完全删除它而不更改程序的含义。

    在readonly属性上指定copy无效。 retainstrong(或更正确地在ARC下,readonly)属性仅影响生成的setter方法,并且编译器不会为readwrite生成setter属性。 (如果您在类扩展中将属性更改为copy,则_options很重要。)

    是的,Editor ivar占用内存(对于_options的每个实例)和符号表中的空格。 由于您没有使用@synthesize ivar,因此您应该完全删除它。您还应该完全删除_options,因此编译器不会为您生成{{1}} ivar。