objective-c – setNilValueForKey错误

前端之家收集整理的这篇文章主要介绍了objective-c – setNilValueForKey错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有四个绑定到模型键路径的文本字段.如果在文本字段中输入了数字,则一切都按计划进行.但是,如果该号码被删除,那么我在控制台中收到错误

[温度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];
}

您可能还想处理类中其他键的值(华氏度,开尔文和摄氏度).

原文链接:https://www.f2er.com/c/114067.html

猜你在找的C&C++相关文章