Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setNilValueForKey error

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];
}
like image 523
wigging Avatar asked Feb 01 '12 20:02

wigging


1 Answers

Your override of -setNilValueForKey: doesn't accomplish anything because it just calls super (which is designed to throw an exception). You need to actually properly handle the nil value. Exactly how you handle it is up to you, but something like this might be reasonable:

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

    [super setNilValueForKey:key];
}

You probably also want to handle nil values for the other keys in your class (Fahrenheit, Kelvin, and Celsius).

like image 97
Andrew Madsen Avatar answered Sep 18 '22 01:09

Andrew Madsen