ios - 没有获得某些键的 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>
解决方案
在您的 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")
}
推荐阅读
- sql - Microsoft SQL Server - 获取最新的价值记录
- php - 返回 Json_Encode 内容并以 HTML 显示
- python - Python OpenCV Lane Detector“无法解压不可迭代的numpy.uint8对象”错误
- python - 根据唯一 ID 将数据从 1 个数据集复制到另一个数据集
- c++ - 在优化代码中查找我的课程副本的位置有什么好的技术?
- sql - Maximo:使用 SQL 查询模拟工作流分配
- javascript - Chai 期望结果等于三个选项之一
- javascript - 是否可以阻止 prettier 在 Promise.try 之后为 .then() {} 语句添加额外的选项卡?
- flutter - 如何在不路由和重建整个屏幕的情况下按下按钮在屏幕上加载数据
- javascript - 从 Json 响应 javascript 创建 flex-box 列