首页 > 解决方案 > 没有获得某些键的 UserDefaults

问题描述

我对 iOS 开发还很陌生,无法找到有关此开发的信息。我创建了 Root.plist 并添加了一些布尔首选项。其中一些我可以使用UserDefaults.standard.bool,但其中一些我总是错误的。

前任。这个电话有效:

UserDefaults.standard.bool(forKey: "zpevnik_hide_identical_chord_sequences")

此调用不会(始终返回 false):

UserDefaults.standard.bool(forKey: "zpevnik_zobrazit_akordy")

主要是手动编辑该文件,因为我发现它比使用 xcode UI 更容易,所以该文件可能有问题?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>StringsTable</key>
    <string>Root</string>
    <key>PreferenceSpecifiers</key>
    <array>
        <dict>
            <key>Type</key>
            <string>PSToggleSwitchSpecifier</string>
            <key>Title</key>
            <string>pref_title_zobrazit_akordy</string>
            <key>Key</key>
            <string>zpevnik_zobrazit_akordy</string>
            <key>DefaultValue</key>
            <true/>
        </dict>
        <dict>
            <key>Type</key>
            <string>PSToggleSwitchSpecifier</string>
            <key>Title</key>
            <string>pref_title_zobrazit_komentare</string>
            <key>Key</key>
            <string>zpevnik_zobrazit_komentare</string>
            <key>DefaultValue</key>
            <true/>
        </dict>
        <dict>
            <key>Type</key>
            <string>PSToggleSwitchSpecifier</string>
            <key>Title</key>
            <string>pref_title_zobrazit_text</string>
            <key>Key</key>
            <string>zpevnik_zobrazit_text</string>
            <key>DefaultValue</key>
            <true/>
        </dict>
        <dict>
            <key>Type</key>
            <string>PSToggleSwitchSpecifier</string>
            <key>Title</key>
            <string>pref_title_multiple_columns</string>
            <key>Key</key>
            <string>zpevnik_multiple_columns</string>
            <key>DefaultValue</key>
            <false/>
        </dict>
        <dict>
            <key>Type</key>
            <string>PSToggleSwitchSpecifier</string>
            <key>Title</key>
            <string>pref_title_hide_identical_chord_sequences</string>
            <key>Key</key>
            <string>zpevnik_hide_identical_chord_sequences</string>
            <key>DefaultValue</key>
            <false/>
        </dict>

    </array>
</dict>
</plist>

标签: iosswift

解决方案


在您的 AppDelegate - 您可以测试密钥的存在 - 如果失败 - 设置它们。

extension UserDefaults {
    
    func valueExists(forKey key: String) -> Bool {
        return object(forKey: key) != nil
    }
    
}

if !UserDefaults.standard.valueExists(forKey: "zpevnik_zobrazit_akordy){
    print("⚠️ warning setting defaults")
    UserDefaults.standard.set(true, forKey: "zpevnik_zobrazit_akordy")
}

推荐阅读