NSUserDefaults和KVO问题 [英] NSUserDefaults and KVO issues

查看:88
本文介绍了NSUserDefaults和KVO问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用NSUserDefaults,我希望在更改特定值时收到通知。为此,我在viewDidLoad中添加了以下行:

I'm using NSUserDefaults in my app and I would like to be notified when a particular value is changed. For that, I added the following lines in viewDidLoad:

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
[settings synchronize];
[settings addObserver:self forKeyPath:@"pref_server" options:NSKeyValueObservingOptionNew context:NULL];

以及要通知的方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    NSLog(@"Change");

    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    if (object == settings && [keyPath isEqualToString:@"pref_server"])
    {
        NSLog(@"Server did change");
    }

}

不幸的是,后者永远不会被调用... @pref_server是我在Root.plist中设置的项目标识符,位于Settings.bundle中。我做错了什么?

Unfortunately, the latter is never called...@"pref_server" is the item identifier I have set in Root.plist, in Settings.bundle. What am I doing wrong?

推荐答案

我建议使用适当的通知: NSUserDefaultsDidChangeNotification

I suggest making use of the appropriate notification: NSUserDefaultsDidChangeNotification.

在XCode中的Apple文档中搜索AppPrefs,它将显示一个示例应用程序,它完全符合您的要求。只需编译并运行!它利用 NSUserDefaultsDidChangeNotification

Search for AppPrefs in the Apple Documentation within XCode and it'll show an example app which does exactly what you want to do. Just compile and run! It makes use of the NSUserDefaultsDidChangeNotification.

这是用于注册观察员的代码:

This is the code being used to register an observer:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(defaultsChanged:)
                                             name:NSUserDefaultsDidChangeNotification
                                           object:nil];

这篇关于NSUserDefaults和KVO问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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