当我覆盖我的类的getter和setter,并在其他地方设置miles
属性时,不会调用setter方法。我做错了什么?
我在这里调用miles
属性
// "entry" is an object that has a property of type CYDistance
if ([unitLabel.text isEqualToString:@"Miles"]) {
entry.distance.miles = s.floatValue;
}
else if ([unitLabel.text isEqualToString:@"Kilometers"]) {
entry.distance.kilometers = s.floatValue;
}
NSLog(@"Miles: %.2f", entry.distance.miles);
NSLog(@"Kilometers: %.2f", entry.distance.kilometers);
Distance.h
#import <Foundation/Foundation.h>
@interface CYDistance : NSObject {
float miles, kilometers;
}
@property float miles;
@property float kilometers;
@end
Distance.m
#import "Distance.h"
@implementation CYDistance
- (float)miles {
return miles;
}
- (float)kilometers {
return kilometers;
}
- (void)setMiles:(float)m {
miles = m;
kilometers = m * 1.609344;
NSLog(@"Set miles");
}
- (void)setKilometers:(float)k {
kilometers = k;
miles = k / 1.609344;
NSLog(@"Set kilometers");
}
@end
答案 0 :(得分:0)
鉴于以下代码......
entry.distance.miles = s.floatValue;
...如果entry.distance
的值为nil
,则不会调用miles
访问者。
答案 1 :(得分:-1)
尝试按以下方式编写实现:
#import "Distance.h"
@implementation CYDistance
@synthesize miles = _miles;
@synthesize kilometers = _kilometers;
- (void)setMiles:(float)m {
_miles = m;
_kilometers = m * 1.609344;
NSLog(@"Set miles");
}
- (void)setKilometers:(float)k {
_kilometers = k;
_miles = k / 1.609344;
NSLog(@"Set kilometers");
}
@end
这种方式在引用伊娃时没有错误。