对的,这是可能的。以下是您在 Swift 中的操作方式:
func loadDefaults() {
let pathStr = NSBundle.mainBundle().bundlePath
let settingsBundlePath = pathStr.stringByAppendingPathComponent("Settings.bundle")
let finalPath = settingsBundlePath.stringByAppendingPathComponent("Root.plist")
let settingsDict = NSDictionary(contentsOfFile: finalPath)
let prefSpecifierArray = settingsDict?.objectForKey("PreferenceSpecifiers") as NSArray
var defaults:[NSObject:AnyObject] = [:]
for prefItem in prefSpecifierArray {
if let key = prefItem.objectForKey("Key") as String! {
let defaultValue:AnyObject? = prefItem.objectForKey("DefaultValue")
defaults[key] = defaultValue
}
}
_userDefaults.registerDefaults(defaults)
}
这将使用 Key 从每个 PreferenceSpecifier 加载 DefaultValue。例如:
<dict>
<key>Type</key>
<string>PSMultiValueSpecifier</string>
<key>Title</key>
<string>Frequency</string>
<key>Key</key>
<string>frequency</string>
<key>DefaultValue</key>
<integer>15</integer>
<key>Titles</key>
<array>
<string>5 minutes</string>
<string>15 minutes</string>
<string>30 minutes</string>
<string>60 minutes</string>
</array>
<key>Values</key>
<array>
<integer>5</integer>
<integer>15</integer>
<integer>30</integer>
<integer>60</integer>
</array>
</dict>
该loadDefaults
函数会将默认值 15 加载到“频率”的用户默认值中。
我建议您loadDefaults
从处理程序中调用您的应用程序委托的didFinishLaunchingWithOptions
函数,如下所示:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
loadDefaults()
return true
}
然后稍后在您的应用程序中,例如在 a 中UITableViewController
,您可以像这样加载用户默认值:
let kFrequency = "frequency"
frequency = _userDefaults.integerForKey(kFrequency)