Properties that cause updates
suggest changeThis object, Shape, has a property image that depends on numberOfSides and sideWidth. If either one of them is set, then image has to be recalculated. Recalculation is presumably slow, and it only needs to happen once if both properties are set, so Shape provides a way to set both properties and recalculate once. That method writes the backing ivars directly.
In Shape.h
@interface Shape : NSObject
// Initializer that takes initial values for the properties.
- (instancetype)initWithNumberOfSides:(NSUInteger)numberOfSides withWidth:(CGFloat)width;
// Method that sets both properties in one call.
// This is useful if setting these properties has expensive side-effects.
// Using a method to set both values at once allows you to have the side-
// effect executed only once.
- (void)setNumberOfSides:(NSUInteger)numberOfSides andWidth:(CGFloat)width;
// Properties using default attributes.
@property NSUInteger numberOfSides;
@property CGFloat sideWidth;
// Property using explicit attributes.
@property(strong, readonly) UIImage * image;
@end
In Shape.m
@implementation Shape
// The variable name of a property that is auto-generated by the compiler
// defaults to being the property name prefixed with an underscore, for
// example "_propertyName". You can change this default variable name using
// the following statement:
// @synthesize propertyName = customVariableName;
- (id)initWithNumberOfSides:(NSUInteger)numberOfSides withWidth:(CGFloat)width {
if ((self = [super init])) {
[self setNumberOfSides:numberOfSides andWidth:width];
}
return self;
}
- (void)setNumberOfSides:(NSUInteger)numberOfSides {
_numberOfSides = numberOfSides;
[self updateImage];
}
- (void)setSideWidth:(CGFloat)sideWidth {
_sideWidth = sideWidth;
[self updateImage];
}
- (void)setNumberOfSides:(NSUInteger)numberOfSides andWidth:(CGFloat)sideWidth {
_numberOfSides = numberOfSides;
_sideWidth = sideWidth;
[self updateImage];
}
// Method that does some post-processing once either of the properties has
// been updated.
- (void)updateImage {
...
}
@end
Assigning object.property = value calls the setter setProperty:. That setter, even if provided by @synthesize, can be overridden, as it is here for numberOfSides and sideWidth. Writing the backing ivar directly (_property, or object->_property) does not call the getter or setter. That is how this example sets two properties and runs the update only once.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents