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内部检查员只是检查选项立即验证并不断更新。

链接地址: http://www.djcxy.com/p/85250.html

上一篇: 等待用户关闭窗口从NSTextField获取值

下一篇: 如何在格式化程序更改其格式时刷新NSTextField?