I have come to find that many of the times in which I want to have a synthesized readonly property, I merely implement the getter method of that property in terms of other variables with no need for an ivar, for example (Note: I am defining ivars in the interface because I am using OmniGraffle UML software and it does not recognize ivars auto-generated by synthesized properties):
@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
In the above Editor class, is it necessary for me to define the _options ivar in the header definition and more importantly does the auto-generated ivar take up memory or space in the symbol table? Also, would it be more efficient to use copy, retain, or no value in this case? Just curious.
First: stop putting your ivar declarations in your
@interface. They belong in your@implementation. See this answer for a detailed explanation.Anyway, given what you've written, your
@synthesize options = _optionshas no effect.That
@synthesizehas two possible effects:It adds an instance variable named
_options, if your class doesn't have one.It generates a getter method,
options, that returns the value of_options, if your class doesn't have a method namedoptions.Since you manually defined the instance variable and the getter, the
@synthesizedoes nothing. You can remove it entirely without changing the meaning of your program.Specifying
copyon a readonly property has no effect. Thecopyandretain(or, more properly under ARC,strong) attributes only affect the generated setter method, and the compiler doesn't generate a setter for areadonlyproperty. (If you change the property toreadwritein a class extension, thencopymatters.)Yes, the
_optionsivar takes up both memory (for each instance ofEditor) and space in the symbol table. Since you're not using the_optionsivar, you should delete it entirely. You should also delete the@synthesizeentirely, so the compiler doesn't generate the_optionsivar for you.