我在Settings.bundle的Root.plist中使用multi_preference设置了一个首选项,如下所示:
<?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>PSMultiValueSpecifier</string>
<key>Key</key>
<string>multi_preference</string>
<key>DefaultValue</key>
<string>Show First Page</string>
<key>Title</key>
<string>My Option</string>
<key>Identifier</key>
<string>myOption</string>
<key>Titles</key>
<array>
<string>Option 1</string>
<string>Option 2</string>
</array>
<key>Values</key>
<array>
<string>Option 1</string>
<string>Option 2</string>
</array>
</dict>
</array>
</dict>
</plist>
当我尝试使用以下代码从列表中获取值时:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *option = [defaults arrayForKey:@"myOption"];
我总是没有回来。
我正在使用模拟器,我在应用程序设置中设置了初始值。
任何人都有任何想法我错过了什么?
由于
iphaaw
答案 0 :(得分:3)
对不起我之前的回答,我误解了这个问题。让我们再试一次。
查看the documentation的PSMultiValueSpecifier,NSUserPreferences的密钥存储在plist中的“Key”键中,而不是“Identifier”键。所以在这种情况下,[defaults arrayForKey:@"multi_preference"]
应该可以为您提供价值。或者您可以像这样更改它,它应该与“myOption”一起使用:
<dict>
<key>Type</key>
<string>PSMultiValueSpecifier</string>
<key>Key</key>
<string>myOption</string>
<key>DefaultValue</key>
<string>Option 1<string>
<key>Title</key>
<string>My Option</string>
<key>Titles</key>
<array>
<string>Text for Option 1</string>
<string>Text for Option 2</string>
</array>
<key>Values</key>
<array>
<string>Option 1</string>
<string>Option 2</string>
</array>
</dict>
答案 1 :(得分:0)
请检查question
问题在于用户与应用程序设置进行交互之前,所选值为nil
。
解决方案是在应用启动时将默认值从Root.plist注册到UserDefaults
。
我已将原始问题的代码更新为Swift 5:
static func registerSettingsDefaults()
{
// Get Settings bundle path
guard let settingsBundle = Bundle.main.path(forResource: "Settings", ofType: "bundle") else {
assertionFailure("Could not find Settings bundle")
return
}
// Get settings plist
let settings = NSDictionary(contentsOfFile: settingsBundle + "/Root.plist")
// Get preferences dictionary
guard let preferences = settings?.object(forKey: "PreferenceSpecifiers") as? [[String: Any]] else {
assertionFailure("Could not find preferences")
return
}
// Filter out default values from Settings
var defaultsToRegister: [String: Any] = [:]
preferences.forEach { dictionary in
if let key = dictionary["Key"] as? String {
defaultsToRegister[key] = dictionary["DefaultValue"] as? String
}
}
UserDefaults.standard.register(defaults: defaultsToRegister)
}
我用didFinishLaunchingWithOptions
称呼它:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{
// Register Settings defaults
registerSettingsDefaults()