xcode - Settings.bundle问题

标签 xcode swift nsuserdefaults root.plist

我在访问我的设置时遇到问题。我向我的 Xcode 项目添加了一个设置包: Root.plist capture

我添加了以下快速代码来访问 name_preference 键: viewDidLoad capture

最佳答案

UserDefaults 因缺少首选项键而崩溃

显式解包是危险的!:如果字符串为空会发生什么?

不好:

let crash = settings.stringForKey("name_preference")!
<小时/>

使用字符串:

let settings = UserDefaults.standard
if let name = settings.string(forKey: "name_preference") {
    print(name)
}

使用对象:

let settings = UserDefaults.standard
if let name = settings.object(forKey: "name_preference") as? String {
    print(name)
}

测试:转到设置并输入字符串:

Settings

<小时/>

► 在 GitHub 上找到此解决方案以及关于 Swift Recipes 的更多详细信息.

关于xcode - Settings.bundle问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34905431/

相关文章:

c - Xcode 无法加载程序?出现错误 : Thread 1: EXC_BAD_ACCESS (code=1, 地址=0x68)

ios - UINavigationbar barTintColor 在 UISplitview 模板中不起作用

ios - 如何从一个屏幕获取数据并将其添加到另一个屏幕上的 UIView 中?

ios - 如何在用户默认设置中保存特定的View Controller?

xcode - 为什么在 Swift 中用关键字 "let"声明常量?

ios - 从 icloud 打开文件时 Swift 4 应用程序崩溃

ios - 如何解决 "ambiguous use of subscript"错误?

ios - 如何在 swift 中将 NSIndexPath 添加到 NSUserDefaults

objective-c - NSUserDefaults 与 CFPreferences,需要考虑什么

ios - Xcode 模拟器 - 导航栏丢失