微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我无法从plist键值中解包一个值

如何解决我无法从plist键值中解包一个值

我是新手,我正在尝试将属性从nsDictionary加载到vTitle

var nsDictionary: NSDictionary?
         if let path = Bundle.main.path(forResource: "AppData",ofType: "plist") {
            nsDictionary = NSDictionary(contentsOfFile: path)
         }
let vTitle:String = nsDictionary["LbVacationsTitle"]

当我调试时,我在nsDictionary中看到了正确的键,但是我不能只拆开一个键的值 LbVacationsTitle的类型是字符串

解决方法

取决于您的样式偏好...

var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData",ofType: "plist") {
    nsDictionary = NSDictionary(contentsOfFile: path)
}
if let dict = nsDictionary {
    let vTitle = dict["LbVacationsTitle"] as? String
    if let vt = vTitle {
        // ...
    }
}

...或...

var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData",ofType: "plist") {
    nsDictionary = NSDictionary(contentsOfFile: path)
}
guard let dict = nsDictionary else {
    print("Couldn't get a valid dictionary")
    return
}
let vTitle = dict["LbVacationsTitle"] as? String
guard let vt = vTitle else {
    print("Couldn't find a string matching LbVacationsTitle")
    return
}
// ...
,

请不要在Swift中使用NSDictionary API来读取属性列表。

PropertyListSerialization(甚至还有PropertyListDecoder

let url = Bundle.main.url(forResource: "AppData",withExtension: "plist")!
let data = try! Data(contentsOf: url)
let dictionary = try! PropertyListSerialization.propertyList(from: data,format: nil) as! [String:Any]
let vTitle = dictionary["LbVacationsTitle"] as! String

由于文件在应用程序捆绑包中是不可变的,因此任何崩溃都表明存在设计错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。