ios - 如何检测 NSUserDefault 的变化?

标签 ios xcode switch-statement nsuserdefaults

我有开关,我想检测是否有任何开关改变了位置,如果进行了改变,我需要开始我的行动。

NSUserDefaults 中切换存储位置

- (IBAction)saveSwitch:(id)sender
{     
    NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
    [defs1 setBool: blackSwitch.on forKey: @"blackKey"];

    NSUserDefaults *defs2 = [NSUserDefaults standardUserDefaults];
    [defs2 setBool: greenSwitch.on forKey: @"greenKey"];

    [[NSUserDefaults standardUserDefaults] synchronize];
}

最佳答案

您可以随时调用 synchronize 发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyAppSettingsChanged" object:self userInfo:nil];

然后在你的其他类(class)听通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppSettingsChanged:) name:@"MyAppSettingsChanged" object:nil];

-(void) onAppSettingsChanged:(NSNotification)notification
{
   // settings changed
}

如果你愿意,你可以通过 NSDictionary调用 postNotificationName 时进入 userInfo其中包含诸如哪些设置已更改之类的信息。

关于ios - 如何检测 NSUserDefault 的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10919885/

相关文章:

ios - 调整 UICollectionView 的大小以使其内容适合 AutoLayout View

ios - Storyboard中的图像 Assets 未显示正确的图像

XCode:如何在测试运行期间禁用 Touchbar 模拟器运行?

c# - 如何在 case 语句中使用范围 C#

ios - 转到另一个 View Controller (iOS)时声音不播放

应用程序 openURL 委托(delegate)后未调用 iOS Google+ SignIn finishedWithAuth

ios - 使用APNs推送服务时 "keyID"是什么

ios - 我可以将 Xcode4 与两个未链接的独立 Apple 开发者帐户一起使用吗?

erlang - 在接收..end中找到多个匹配项以查找..of?

ios - 使用 switch case 将一个数组中的字符串与另一个数组进行比较