Cocoa - 关于NSUserDefaults的通知值的变化? [英] Cocoa - Notification on NSUserDefaults value change?

查看:148
本文介绍了Cocoa - 关于NSUserDefaults的通知值的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个键MyPreference,通过NSUserDefaults存储相应的值。

Let's say I have a key @"MyPreference", with a corresponding value stored through NSUserDefaults.

当值被修改时,有没有办法被通知?

Is there a way to be Notified when the value is modified?

还是可以通过绑定完成? (但是,这种情况下,我希望我的对象被通知这个更改,以便我可以执行其他任务。)

Or could it be done through bindings? (But this case, instead of binding the value to a UI element, I wish my object to be notified of the change, so that I can perform other tasks.)

我知道NSUserDefaultsDidChangeNotification可以被观察,但这似乎是一个全有或全无的方法,并且似乎没有一个机制来获得被修改的特定键值对。 (随意更正。)

I am aware that NSUserDefaultsDidChangeNotification can be Observed, but this appears to be a all-or-nothing approach, and there does not appear to be a mechanism there to get at the specific key-value-pair that was modified. (Feel free to correct.)

推荐答案

花一整天寻找答案,只有在提出问题10分钟后才能找到答案...

Spent all day looking for the answer, only to find it 10 minutes after asking the question...

通过Key-Value-Observing跨解决方案:

Came across a solution through Key-Value-Observing:

[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self
    forKeyPath:@"values.MyPreference"
    options:NSKeyValueObservingOptionNew
    context:NULL];

或者,更简单的方法是下面的注释:

Or, more simply (per comment below):

[[NSUserDefaults standardUserDefaults] addObserver:self
                                        forKeyPath:@"MyPreference"
                                           options:NSKeyValueObservingOptionNew
                                           context:NULL];

这篇关于Cocoa - 关于NSUserDefaults的通知值的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆