ios - Xcode 在多个 View Controller 中加载 NSUserDefaults

标签 ios nsuserdefaults multiple-views

我进行了彻底的研究,但似乎没有找到我正在寻找的答案。希望有人能帮忙。

我的应用程序中有多个 View Controller ,其中一个是“选项” View ,用户可以在其中通过分段控件更改某些设置,例如背景颜色。单击后,用户单击按钮将他们的偏好颜色保存到 NSUserDefaults。这非常有效,下次打开应用程序时,仍会选择正确的颜色。但仅在选项 View Controller 中。

我怎样才能让这个选定的背景颜色加载到我的其他 View Controller 中?我似乎没有通过将它实现到我的其他 View 的 ViewDidLoad 中来运行它,就像我在选项 View 中所做的那样(见下文)。

我在options.m中的代码如下:

- (IBAction)changeColor {
    switch (colorControl.selectedSegmentIndex) {
        case 0:
            [colorView setBackgroundColor:[UIColor redColor]];
            break;
        case 1:
            [colorView setBackgroundColor:[UIColor blackColor]];
            break;
        case 2:
            [colorView setBackgroundColor:[UIColor brownColor]];
            break;  
        default:
            break;
    }
}

- (IBAction)saveDefaultColor {
    int defaultColorInteger = colorControl.selectedSegmentIndex;

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:defaultColorInteger forKey:@"defaultColor"];
    [userDefaults synchronize];
 }

以上是控制和保存按钮。在我的 ViewDidLoad 中,我包含了以下内容:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
int defaultColorInteger = [userDefaults integerForKey:@"defaultColor"];

[colorControl setSelectedSegmentIndex:defaultColorInteger];

switch (colorControl.selectedSegmentIndex) {
    case 0:
        [colorView setBackgroundColor:[UIColor redColor]];
        break;
    case 1:
        [colorView setBackgroundColor:[UIColor blackColor]];
        break;
    case 2:
        [colorView setBackgroundColor:[UIColor brownColor]];
        break;

    default:
        break;

这完全符合我的要求,但我不能让它在我的其他 View 中工作。 谁能帮我解决我似乎缺少的东西?非常感谢

最佳答案

我认为您需要检查其他 View 中的键值,因为 NSUserDefaults 为整个应用程序而不是单个 View 保存数据。可能是您没有正确放置 key 。

关于ios - Xcode 在多个 View Controller 中加载 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21111130/

相关文章:

ios - 使用 NSMutableArray 保存和加载 MapAnnotation 引脚

ios - Swift 中的 EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

ios - 多个 UIViews,传递方法

javascript - 拥有可以使用 AngularJS 从多个位置触发的动态页脚的最佳方式是什么

ios - 使用时属性显示为零,但在使用前打印到调试控制台?

ios - TWTRTweetTableViewCell 无法检测链接 - Fabric TwitterKit

ios - 在模拟器上卸载应用程序后未清除 NSUserDefaults

c# - 在 UWP 中完全关闭辅助 View

ios - 点击标签时同时调用和短信选项

ios - 类型 'Int' 没有下标成员