I have two attributes, TKelvin and TCelsius.
When I change in my window TKelvin, TCelsius should be updated with TKelvin - 273.15 and when I change in my window TCelcius, TKelvin should be updated with TCelcius + 273.15 automatically.
I tried the following code:
- (void)setTKelvin:(NSNumber *)newTKelvin;
{
NSNumber *number;
[self willChangeValueForKey:@"TKelvin"];
[self setPrimit开发者_运维技巧iveT:newTKelvin];
[self didChangeValueForKey:@"TKelvin"];
if ([newTKelvin doubleValue] != [[self TCelsius] doubleValue] + 273.15) {
double tCelsiusValue = [newT doubleValue] - 273.15;
number = [NSNumber numberWithDouble:tCelsiusValue];
[self setValue:number forKey:@"TCelsius"];
}
}
This works for the entity (TCelcius is altered) but TCelsius in not automatically updated in the window. What can I do?
If TCelcius is always based on the TKelvin value, it would be simpler to store only one of the values and calculate the other as needed. You can remove the TCelcius property from the object model. This will keep the two values synchronized.
Define the TCelcius property in the header
@property (assign) NSNumber *TCelcius;
Add keyPathsForValuesAffectingValueForKey to allow KVO and Bindings to know that your TCelcius value is dependent on the TKelvin value.
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];
if ([key isEqualToString:@"TCelcius"]) {
NSSet *affectingKeys = [NSSet setWithObjects:@"TKelvin", nil];
keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKeys];
}
return keyPaths;
}
And then add a getter and setter for the TCelcius value that redirects to the TKelvin value:
- (NSNumber *)TCelcius {
return [NSNumber numberWithDouble:[[self TKelvin] doubleValue]-273.15];
}
+ (void)setTCelcius:(NSNumber *)newTCelcius {
[self setTKelvin:[NSNumber numberWithDouble:[[self newTCelcius] doubleValue]+273.15]];
}
Make sure to remove your current setter and use the dynamic getter and setter for the TKelvin value.
精彩评论