1

当我为我的类覆盖 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);

距离.h

#import <Foundation/Foundation.h>

@interface CYDistance : NSObject {
    float miles, kilometers;
}

@property float miles;
@property float kilometers;

@end

距离.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
4

2 回答 2

0

鉴于以下代码...

entry.distance.miles = s.floatValue;

...如果值为entry.distanceis nil,则miles不会调用访问器。

于 2012-07-06T19:22:37.280 回答
-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

这样在引用 ivars 时就不会出错。

于 2012-07-06T18:06:34.997 回答