ios - 为什么我的 User Defaults bool 没有在第一次启动应用程序时设置?

标签 ios swift userdefaults

我有一个 UserDefault Bool 用于音乐播放。

第一次启动时,我尝试将 bool 设置为 true,就像这样...

if launchedBefore {

        // Do nothing.

    } else {

        UserDefaults.standard.set(true, forKey: "musicOn")
        print("music is \(musicOn)")
        UserDefaults.standard.set(true, forKey: "alreadylaunched")

    }

这是在 viewDidAppear() 中。

问题是它在第一次启动时没有设置为真,不管我在哪里设置 bool,它可能没有 launchedBefore 检查,它仍然没有在第一次设置.

我不明白为什么这行不通? musicOn 在第一次启动时总是等于 false,然后在第二次启动时,它是真的吗?

如有任何见解,我们将不胜感激。谢谢!

最佳答案

对我有用的是让 var musicOn 再次等于用户默认的 bool。

if launchedBefore {

        // Do nothing.

    } else {

        UserDefaults.standard.set(true, forKey: "musicon")
        print("music is \(UserDefaults.standard.bool(forKey: "musicon"))")

        musicOn = UserDefaults.standard.bool(forKey: "musicon") // Stating it again works to update the bool.

        UserDefaults.standard.set(true, forKey: "alreadylaunched")

    }

var musicOn 已经在任何函数之外实例化了,看来只需要重新设置一下。

感谢您的评论!

关于ios - 为什么我的 User Defaults bool 没有在第一次启动应用程序时设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233411/

相关文章:

ios - 无法更改 FBSDKLoginKit 中登录按钮的高度?

swift - libc++abi.dylib : terminating with uncaught exception of type NSException Alamofire

ios - 全局缓存服务器数据并刷新 View

iOS:如何检测Ipad是否放入特殊框架中

swift - NSURL 失败初始化器 initWithString : does not return nil on empty String in Swift

swift - iTunesLibrary 获取所有音乐

arrays - 如何在 swift 中将 json 数组保存和检索为用户默认值?

c# - 为什么统一增加 transform.position 会导致 iOS 抖动?

android - 相机在 Flex 模拟器中运行良好,但在设备上运行不佳

ios - 从 StoryBoard 获取对 TableViewController 中左按钮的引用