I have four textfields that bind to the model key path. If a number is typed into the textfield, everything works as planned. However, if the number is deleted then I get an error in the console with:
[Temperature 0x1003144b0 setNilValueForKey]: could not set nil as the value for the key rankine
I tried to fix this using setNilValueForKey but it doesn't seem to work (see code at bottom of Temperature.h file). Any suggestions on how to fix this would be helpful.
#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
and
#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
...answer based on comments...
- (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];
}