Reputation: 47
I have written a setter that is not working as expected. I am reading in statistics from a file and populating the properties of my SVTeam object with these stats. However some of the properties need to be calculated (as they are not supplied in the files). One of these properties holds the home winning percentage for a given team. I do not need to supply an argument for the setter. Two questions:
null
?SVTeam.h
@interface SVTeam : NSObject
@property (weak, nonatomic) NSNumber *homePercentage;
...
...
SVTeam.m
#import "SVTeam.h"
@implementation SVTeam
@synthesize homePercentage = _homePercentage;
...
...
-(void) setHomePercentage
{
float wins = [_homeWins floatValue];
float losses = [_homeLosses floatValue];
float ties = [_homeTies floatValue];
float winPercentage = wins / (wins+losses+ties);
self.homePercentage = [NSNumber numberWithFloat:winPercentage];
}
Upvotes: 1
Views: 96
Reputation: 11016
To expand on Garfield81's answer:
If you want to override the setter synthesized by clang for you homePercentage
property, you need to implement -(void)setHomePercentage:(NSNumber *)homePercentage;
in your class.
Apple documentation on properties.
To answer your two questions:
1) since I'm NOT supplying an argument in my setter is it still truly a setter in an objective-c sense?
No. The synthesized setters takes an unique argument of the same type of the propery and are named set<CapitalizedPropertyName>
. What you did is declare a new method.
2) even it if is not a true setter why does the code below still leave the properties as null
There is not apparent reason for homePercentage
to stay nil
(not null
) from the code you provided. Are you sure your custom method gets called? (remember that when using the dot notation (self.homePercentage
), this is -(void)setHomePercentage:(NSNumber *)homePercentage;
which is called, not your -(void)setHomePercentage;
).
Note also that you don't need to add @synthesize homePercentage = _homePercentage;
unless you override both the getter and the setter.
Upvotes: 3
Reputation: 521
Since homePercentage is a calculated value based on other properties you could make it a readonly property and you would have your calculation logic in the getter instead. If you leave it as a setter then your consumers would have to make sure to call the setter first and call the getter to retrieve the value.
@property(nonatomic,readonly) NSNumber *homePercentage;
And your getter definition would be
- (NSNumber *)homePercentage
{
...
return [NSNumber numberWithFloat:winPercentage];
}
Upvotes: 7