ios - Swift:如何在 plist 中的数组中读取多个数组?

标签 ios arrays swift plist

这是我的plist

Collection View

pic1

使用 Swift 3,我正在读取 plist 以用这段代码完美地填充我的数组,但我不知道如何在 plist 的根数组中包含数组时访问它

当根是数组时我用来读取的代码

var mainGroup = [String]()

var myArray: [String]?
if let path = Bundle.main.path(forResource: "items", ofType: "plist") {
    myArray = NSArray(contentsOfFile: path) as? [String]
}

mainGroup = myArray!

但是在这个 plist 中,要读取的数组不仅仅是根。我想在我的 Collection View 中读取根有多少个数组,我在 numberOfItemsInSectioncellForItemAtdidSelectItemAt 中使用它。我还想读取数组中的项目,以便在选择项目时在集合的详细 View 中显示它。

结论:我想详细了解根数组中有多少个数组以在 .count 中使用它,以及如何访问数组中的项目以在另一个 View Controller 中显示它。要访问一个数组,它将是 array[2] 但如果我想显示字符串 "Jeans"和 "4"等,那将如何工作。谢谢

最佳答案

Swift 中推荐的读取属性列表文件的方法是 PropertyListSerialization。它避免了使用 Foundation NSArray

代码打印内部数组中的节号和所有项目。

如果属性列表应该填充 TableView ,我建议将内部数组声明为字典。

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

    for (index, section) in sections.enumerated() {
        print("section ", index)
        for item in section {
            print(item)
        }
    }
} catch {
    print("This error must never occur", error)
}

关于ios - Swift:如何在 plist 中的数组中读取多个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46290998/

相关文章:

ios - iOS 中的多点连接框架问题

arrays - 如何在 GNUplot 中定义和访问数组?

ios - 两个几乎相同的 UITapGestureRecognizers 之一的 Action 比另一个慢得多

linux - NSSet(数组: myArray) works on OS X but crashes in Ubuntu

ios - 如何创建Core Data数据库swift 4

ios - 如何在 XCode 中复制文件?

ios - 在 iOS 10 上未收到推送通知,但在 iOS 9 及之前的版本上有效

php - 循环数组没有给出所需的结果

javascript - 即使我将 'objects' 插入数组,数组长度仍为 0

ios - 如何检索 Swift 中所有已安装键盘的列表?