在Objective C中没有调用Setter方法

时间:2012-07-06 17:11:56

标签: objective-c methods override setter

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

2 个答案:

答案 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

这种方式在引用伊娃时没有错误。