简体   繁体   中英

How to refresh NSTextField when its formatter changes its format?

I have a couple of NSTextFields that use bindings to get their values. Each textfield has a custom NSFormatter attached which is used to format the value.

Now I want to change the format of this NSFormatter, I do this by setting a key in NSUserDefaults. The formatter listens to NSUserDefaultsDidChangeNotification. This works as long as the value that backs the binding is changed. If that value is not changed the NSTextField does not update.

What is the correct way to refresh a NSTextField if its formatter has changed its format?

In a best case scenario I need neither references to the NSTextField nor to the NSFormatter. Throughout the app there are various temperature labels that should all switch their format. I would love to be able to start the “bindings refresh” from inside the NSFormatter. Maybe I am missing a NSNotification?

I tried to send willChangeValueForKey: and didChangeValueForKey: KVO notifications, but that did not work.
Right now I'm using a rather hacky way, I just change the value a tiny bit.

- (IBAction)temperatureMenuDidSelect:(NSMenuItem *)sender {
    [[NSUserDefaults standardUserDefaults] setInteger:sender.tag forKey:MBUserDefaultsTemperatureSystemKey];
    // refresh. this is an ugly hack, maybe there is a nicer way?
    self.selectedDevice.temperature += 0.000001;
//    [self.selectedDevice willChangeValueForKey:@"temperature"];
//    [self.selectedDevice didChangeValueForKey:@"temperature"];
}

As you can imagine both ways are not a good idea. It works right now because I am just displaying the value. But I'm blocking future options to make use of KVO for things that rely on the integrity of the data, eg a temperature history, so I want to avoid to send fake value change events.

have you tried:

self.selectedDevice.temperature = self.selectedDevice.temperature;

It's maybe a question of what is bound to what here. Is your NSTextField bound by the keypath of selectedDevice.temperature ? maybe you need to use @"selectedDevice.temperature" for the key parameter.

I have never had a problem using willChangeValueForKey: followed by didChangeValueForKey: I think maybe the problem is you should be using @"_temperature" for the key instead of @"temperature" .

Then again I have never tried calling those methods on an object other than self . have you tried implementing an update method inside selectedDevice to do the KVO notifications? I don't know why it would make a difference, but I've never had a problem refreshing values

在检查器内部的xib中,只需检查选项即可立即进行验证并不断进行更新。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM