简体   繁体   English

Xcode Swift 如何从我的自定义 plist 文件中打印一个值?

[英]Xcode Swift how do I print a value form my custom plist file?

Ok I have read so much about NSArray NSDictionary I'm lost now, what I want is to print the value 'name' from the first array item of my custom plist.好的,我已经阅读了很多关于 NSArray NSDictionary 的内容,我现在迷路了,我想要的是从我的自定义 plist 的第一个数组项中打印值“名称”。

This is my plist:这是我的清单:

在此处输入图像描述

and this is my code in my ViewController.swift:这是我在 ViewController.swift 中的代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let path = Bundle.main.path(forResource: "test", ofType: "plist")
        let dic = NSArray(contentsOfFile: path!)
        print(dic?.firstObject)
    }
}

in my console I see:在我的控制台中,我看到:

Optional({
    active = 0;
    name = "John Doe";
})

I would think that print(dic?.firstObject["name"]) would do the trick but I get an error: Value of type 'Any?'我认为print(dic?.firstObject["name"])可以解决问题,但我得到一个错误: 'Any?' 类型的值has no subscripts没有下标

So how do I print the values of name and active of my first array?那么如何打印我的第一个数组的nameactive值?

I know there are lots of answers on SO regarding this question, that's the reason I got so far.我知道关于这个问题有很多答案,这就是我到目前为止的原因。 but I just don't know how to fix this.但我只是不知道如何解决这个问题。

Kind regards,亲切的问候,

Ralph拉尔夫

First of all please never use the NSArray/NSDictionary related API in Swift to read a property list.首先请不要使用 Swift 中的NSArray/NSDictionary相关的 API 来读取属性列表。 You are throwing away the type information.您正在丢弃类型信息。

However you can read the values with但是,您可以使用

let array = NSArray(contentsOfFile: path!) as! [[String:Any]]
for item in array {
    let name = item["name"] as! String
    let active = item["active"] as! Bool
    print(name, active)
}

The dedicated and recommended API is PropertyListSerialization :专用和推荐的 API 是PropertyListSerialization

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

A better way is the Codable protocol and PropertyListDecoder更好的方法是Codable协议和PropertyListDecoder

struct User : Decodable {
    let name : String
    let active : Bool
}


override func viewDidLoad() {
    super.viewDidLoad()
    
    let url = Bundle.main.url(forResource: "test", withExtension: "plist")!
    let data = try! Data(contentsOf: url)
    let array = try! PropertyListDecoder().decode([User].self, from: data)
    for item in array {
       print(item.name, item.active)
    } 
}

The code must not crash.代码不得崩溃。 If it does you made a design mistake如果是这样,你就犯了设计错误

To use subscripts you first need to cast the object returned by要使用下标,您首先需要转换返回的 object

dic?firstObject

to a dictionary, you can also unwrap the optional at this point.到字典,你也可以在这一点上解开可选的。

if let item = dic?firstObject as? [String: Any] {
   print(item["name")
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM