检测NSUserDefaults上的更改

我正在开发一个iOS应用程序与最新的SDK。

我想知道NSUserDefaults上的属性NSUserDefaults更改它的值。

我已经find了这个 ,但它是特定的MAC:

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

我怎么能在iOS上做到这一点?

用下面的代码片段试试NSUserDefaultsDidChangeNotification

 - (id)init { self = [super init]; if(self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil]; } return self; } - (void)defaultsChanged:(NSNotification *)notification { // Get the user defaults NSUserDefaults *defaults = (NSUserDefaults *)[notification object]; NSLog(@"%@", [defaults objectForKey:@"yourIntrestedObject"]); } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } 

使用NSUserDefaultsDidChangeNotification通知有关更改用户默认值的信息:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsDidChange:) name:NSUserDefaultsDidChangeNotification object:nil]; // notification - (void)defaultsDidChange:(NSNotification *)aNotification { // } 

使用KVO通知有关用户默认值的特定更改:

 [[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"APXMyPropertyIamInterestedInKey" options:NSKeyValueObservingOptionNew context:NULL]; // KVO handler -(void)observeValueForKeyPath:(NSString *)aKeyPath ofObject:(id)anObject change:(NSDictionary *)aChange context:(void *)aContext { // } 

这里是解决scheme,我发布如何在Swift中做到这一点,也得到了userInfo, Stackoverflow的Swift链接

在Xcode帮助中, UserDefaults类(NSUserDefaults的swifty名称)的概述明确指出:

您可以使用键值观察来为感兴趣的特定键注册观察者,以便将所有更新通知给本地默认数据库。 有关更多详细信息,请参阅键值观察编程指南。

我会看看我能不能拿出一个快速的代码示例,但堆栈溢出必须充满KVO样本。