我有四个文本字段绑定到模型密钥路径。如果输入了一个数字,那么一切都按计划工作。但是,如果删除了该号码,则控制台中会出现以下错误:
[温度0x1003144b0 setnilvalueforkey]:无法将nil设置为密钥rankine的值
我试图用setnilvalueforkey来修复这个问题,但它似乎不起作用(参见temperature.h文件底部的代码)。任何关于如何解决这个问题的建议都是有帮助的。

#import <Foundation/Foundation.h>

@interface Temperature : NSObject {
    double celsius;
}

- (void)setCelsius:(double)degreesC;
- (double)celsius;

- (void)setKelvin:(double)degreesK;
- (double)kelvin;

- (void)setFahrenheit:(double)degreesF;
- (double)fahrenheit;

- (void)setRankine:(double)degreesR;
- (double)rankine;
@end


#import "Temperature.h"

@implementation Temperature

+ (NSSet *)keyPathsForValuesAffectingFahrenheit {
    return [NSSet setWithObject:@"celsius"];
}

+ (NSSet *)keyPathsForValuesAffectingKelvin {
    return [NSSet setWithObject:@"celsius"];
}

+ (NSSet *)keyPathsForValuesAffectingRankine {
    return [NSSet setWithObject:@"celsius"];
}

- (void)setCelsius:(double)degreesC {
    celsius = degreesC;
}

- (double)celsius {
    return celsius;
}

- (void)setKelvin:(double)degreesK {
    [self setCelsius:degreesK - 273.15];
}
- (double)kelvin {
    return [self celsius] + 273.15;
}

- (void)setFahrenheit:(double)degreesF {
    [self setCelsius:(degreesF - 32) / 1.8];
}
- (double)fahrenheit {
    return [self celsius] * 1.8 + 32;
}

- (void)setRankine:(double)degreesR {
    [self setCelsius:(degreesR - 491.67) * 5/9];
}
- (double)rankine {
    return ([self celsius] + 273.15) * 9/5;
}

- (void)setNilValueForKey:(NSString *)rankine {
    [super setNilValueForKey:rankine];
}
@end

…根据评论回答…
- (void)setNilValueForKey:(NSString*)key {
    if ([key isEqualToString:@"celsius"]) return [self setCelsius: 0];
    if ([key isEqualToString:@"fahrenheit"]) return [self setFahrenheit: 0];
    if ([key isEqualToString:@"kelvin"]) return [self setKelvin: 0];
    if ([key isEqualToString:@"rankine"]) return [self setRankine: 0];

    [super setNilValueForKey:key];
}

最佳答案

您对-setnilvalueforkey:的重写没有完成任何事情,因为它只调用super(设计用于引发异常)。你需要正确地处理nil值。具体如何处理取决于你自己,但这样的事情可能是合理的:

- (void)setNilValueForKey:(NSString*)key
{
    if ([key isEqualToString:@"rankine"])
    {
        self.rankine = 0;
        return;
    }

    [super setNilValueForKey:key];
}

您可能还希望处理类中其他键(华氏度、开尔文和摄氏度)的零值。

08-19 23:31