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

查看:33
本文介绍了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?

或者可以通过绑定来完成吗?(但在这种情况下,我希望将更改通知我的对象,而不是将值绑定到 UI 元素,以便我可以执行其他任务.)

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天全站免登陆