Within the last year, I’ve been working with other people on some Objective-C projects for the first time.
Occasionally (and increasingly) I’m seeing other people overriding getter/accessor methods, AND containing implementation code in this method! To me this is crazy town, as this is the whole point of having a setter…it also means that the property being set in the setter will just be overridden in the getter, and therefor pointless.
Are these people behaving badly, or am I the one who’s missing something? Is there EVER a need to override a synthesized property’s getter method?
Example:
@synthesize width;
- (CGFloat)width {
NSNumber *userWidth = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_WIDTH"];
if (userWidth != nil)
{
width = [NSNumber floatValue];
}
//Shouldn't the above lines be done in the SETTER? I have SET the property!
//Why would I ever need to write anything BUT the below line??
return width;
}
- (void)setWidth:(CGFloat)newWidth {
//THIS is where you do the the setting!
width = newWidth;
}
UPDATE:
Ok width is a bad example. Too many people are getting caught up on the semantics of “what the variable is” and “don’t include get in objective-c accessors”. So I’ve updated the above example to ignore the irrelevant semantics, and concentrate on the concept. The concept being…is there any example when you’d want to override the GETTER (not setter, getter only. I override the setter many times, this question is about the getter)?
Returning another property such as layer (as mentioned below) is a genuine example. But more specifically is there ever a need to SET the property in a GETTER? This is some of the weirdness that I’m seeing, so i’ve updated the getter above to pull a value from the NSUserDefaults to aid my point…
The first issue is you don’t want to use getWidth. The pattern in objC is name and setName. Do not use getName. It messes up binding and KVO.
Also, if it’s just setting/getting the iVar, there’s no reason to override. If you’re doing extra processing/validation then it may be Ok to override.
EDIT:
You should also try to avoid setting data and doing heavy processing in the getter. A getter is supposed to encapsulate some state and return data. The expectation is that it’s very light weight. Heavy processing and/or modifications should be done in methods or setters. For example, folks set debug watches on getters and don’t expect heavy processing and modification of state.