我正在一个需要从.plist
恢复保存的数据的项目中,但是我遇到一个错误无法用索引类型为'String'的下标'Dictionary'类型的值] 。我正在尝试解决问题,但是不幸的是我不知道如何解决。我尝试了一些在stackoverflow中到达这里的解决方案,但是没有成功。请帮我,因为这是我第一次创建一个恢复数据的功能。谢谢
@objc func restoreSucceed() {
performSelector(inBackground: #selector(stopIndicator), with: nil)
//エラーアラートビューの表示
let alertController = UIAlertController(title: "", message: "リストアが完了しました \n (Restore completed)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
if floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1 {
var pref = UserDefaults.standard
//ローカルplist格納先を取得
let strWorkPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let strPlistPath = "\(strWorkPath)/\(S_DIRECTORY_NAME)/\(S_PLIST_NAME)"
let dicPref = NSDictionary(contentsOfFile: strPlistPath) as Dictionary?
if let key1 = (dicPref as NSDictionary?)?.keyEnumerator() {
for key in key1 {
let strKey = key as? String
pref.set(dicPref?[strKey ?? ""], forKey: strKey ?? "")
}
}
pref.synchronize()
}
navigationController?.popViewController(animated: true)
}
用dicPref?[strKey ?? ""]
替换dicPref?[strKey as! NSString]
注意:如果可能,请避免强行展开。
使用以下内容
pref.set(dicPref?[strKey! as NSString], forKey: strKey ?? "")
@@ Roy的回答是正确的,但会警告您打开包装纸
尝试下面的代码
var pref = UserDefaults.standard
let strWorkPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let strPlistPath = "\(strWorkPath)/\(S_DIRECTORY_NAME)/\(S_PLIST_NAME)"
if let dicPref = NSDictionary(contentsOfFile: strPlistPath) as? Dictionary<String, AnyObject> {
// use swift dictionary as normal
if let key1 = (dicPref as NSDictionary?)?.keyEnumerator() {
for key in key1 {
if let strKey = key as? String {
pref.set(dicPref[strKey], forKey: strKey)
}
}
}
}
pref.synchronize()
替换:
let dicPref = NSDictionary(contentsOfFile: strPlistPath) as Dictionary?
with:
let dicPref = NSDictionary(contentsOfFile: strPlistPath)
。
let pref = UserDefaults.standard
let dicPref = NSDictionary(contentsOfFile: "")
if let key1 = dicPref?.keyEnumerator() {
for key in key1 {
let strKey = key as? String
pref.set(dicPref?[strKey ?? ""], forKey: strKey ?? "")
}
}