I have a setter method (setMinimumNumberOfSides) that I want to override after using synthesize. In it, I’m putting in a constraint on the instance variable to make sure the int is within certain bounds.
Later in a custom init method, I’m setting another instance variable (numberOfSides), but I need to make sure minimumNumberOfSides and maximumNumberOfSides was set properly within bounds. I tried changing the return value on the setter to a BOOL, so I could pass back a YES or NO if it succeeded/failed, but that created a conflicting method, I’m guessing because I’m using synthesize and overriding the setter.
How can I get the info out easily to check to see if the setter was called and returned successfully?
-(void)setNumberOfSides:(int)sides { if ((sides < maximumNumberOfSides) && (sides > minimumNumberOfSides)) { numberOfSides = sides; } else NSLog (@'Invalid number of sides: %d is outside the constraints allowed', sides); } -(void)setMinimumNumberOfSides:(int)minimum { if (minimum > 2) minimumNumberOfSides = minimum; } -(void)setMaximumNumberOfSides:(int)maximum { if (maximum <= 12) maximumNumberOfSides = maximum; } -(id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max { if (self = [super init]) { self.minimumNumberOfSides = min; self.maximumNumberOfSides = max; self.numberOfSides = sides; } return self; }
You don’t have to synthesize numberOfSides if you’re planning on implementing the getter and setter. Without
@synthesize numberOfSidesyou can return a BOOL if you choose. You’ll need to declare the getter/setter in your interface accordingly.BTW, another approach would be to use the synthesized getter/setter and add a separate method
-(BOOL)isNumberOfSidesValidwhich performs this check.