简体   繁体   English

“无法下标‘字典’类型的值<nsobject, anyobject> ' 索引类型为 'String' 错误</nsobject,>

[英]"Cannot subscript a value of type 'Dictionary<NSObject, AnyObject>' with an index of type 'String" error

I been working on a project that needs to restore the saved data from .plist , but I am encountering an error Cannot subscript a value of type 'Dictionary' with an index of type 'String' in my code.我一直在做一个需要从.plist恢复保存的数据的项目,但是我遇到了一个错误Cannot subscript a value of type 'Dictionary' with an index of type 'String' in my code。 I am trying to solve it but unfortunately I don't know how.我正在尝试解决它,但不幸的是我不知道如何解决。 I tried some solution I got here in stackoverflow but It didn't worked out.我尝试了一些我在stackoverflow中找到的解决方案,但没有成功。 Please help me with this because It is my first time to create a function to restore data.请帮助我,因为这是我第一次创建恢复数据的功能。 Thank you谢谢

错误在这里

 @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)
}

Use following使用以下

pref.set(dicPref?[strKey! as NSString], forKey: strKey ?? "")

@Roy's answer is correct but it will give you warning of unwraps @Roy 的回答是正确的,但它会给你警告 unwraps

Replace dicPref?[strKey?? ""]替换dicPref?[strKey?? ""] dicPref?[strKey?? ""] with dicPref?[strKey as! NSString] dicPref?[strKey?? ""]dicPref?[strKey as! NSString] dicPref?[strKey as! NSString]

NB: Avoid force unwrapping if possible.注意:如果可能,避免强行展开。

Your code uses a lot of inappropriate objective-c-ish API.您的代码使用了很多不合适的objective-c-ish API。

This is the recommended Swift way to read and parse a property list file这是推荐的 Swift 读取和解析属性列表文件的方式

if #available(iOS 7.1, *) {   
    //ローカルplist格納先を取得
    do {
        let strWorkURL = try FileManager.default.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let strPlistURL = strWorkURL.appendingPathComponent("\(S_DIRECTORY_NAME)/\(S_PLIST_NAME)")
        let strPlistData = try Data(contentsOf: strPlistURL)
        guard let dicPref = try PropertyListSerialization.propertyList(from: strPlistData, format: nil) as? [String:Any] else { return }
        for (key, value) in dicPref {
            UserDefaults.standard.set(value, forKey: key)
        }
    } catch { print(error) }
}

And don't use performSelector(inBackground:) either.也不要使用performSelector(inBackground:) Use GCD使用 GCD

DispatchQueue.global().async {
    stopIndicator()
}

Try below code试试下面的代码

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()

replace:代替:

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 ?? "")
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误无法下标“字典”类型的值 <NSObject, AnyObject> &#39;的索引类型为&#39;String&#39; - Error Cannot subscript a value of type 'Dictionary<NSObject, AnyObject>' with an index of type 'String' 不能下标'[NSObject:AnyObject]类型的值吗?索引类型为'String' - Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String' 无法用索引类型“字符串”下标“ [NSObject:AnyObject]”类型的值 - Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'String' 无法下标&#39;[NSObject:AnyObject]类型的值?” 索引类型为&#39;String&#39;的Swift错误 - Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String' Swift Error 无法用索引为“ NSKeyValueChangeKey”的下标“ [NSObject:AnyObject]”的值 - Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'NSKeyValueChangeKey' 无法下标[AnyObject]的值? 索引类型为String - Cannot subscript a value of [AnyObject]? with an index of type String 不能下标类型为[String:AnyObject]的值?索引类型为String - Cannot subscript a value of type [String: AnyObject]? with an index of type String 迅速:无法下标[字典式]的值 <String, AnyObject> ],其索引类型为字符串 - swift: cannot subscript a value of type [Dictionary<String, AnyObject>] with an index of type string 无法使用索引类型为“String”的类型&#39;[String:AnyObject]&#39;下标值 - Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String' 无法用索引类型“ String”下标“ [String:AnyObject]”类型的值 - Cannot subscript a value of type '[String: AnyObject]' with an index of type 'String'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM