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

时间:2017-09-19 02:46:56

标签: ios arrays swift plist

这是我的plist

收藏视图

pic1

使用Swift 3,我正在阅读plist以完全填充我的数组代码但我不知道如何在根数组中有数组时访问plist

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

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中,有更多的数组要读取而不仅仅是根。我想读一下root有多少个数组,所以在我的集合视图中我在numberOfItemsInSectioncellForItemAtdidSelectItemAt中使用它。我还想读取数组中的项目,以便在选择项目时在集合的详细视图中显示它。

结论:我想读取根数组中有多少数组在.count中使用它以及如何访问数组中的项目以将其作为详细信息显示在另一个视图控制器中。要访问数组,它将是array[2],但如果我想显示字符串“Jeans”和“4”等,那将如何工作呢。谢谢

4 个答案:

答案 0 :(得分:5)

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

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

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

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

答案 1 :(得分:1)

我分别用rootArray&添加评论子阵 enter image description here

   override func viewDidLoad() {
        super.viewDidLoad()
        readPlist()
    }
    func readPlist(){
        let path = Bundle.main.path(forResource: "SampleData", ofType: "plist")
        let rootArray = NSArray(contentsOfFile: path!)!
        print(rootArray.count)//Gives count for total objects. You can use in number of rows

        for data in rootArray {
            let subArray = data as? NSArray ?? []
            print(subArray.count)//Gives you subarray count
            for value in subArray {
                print("objects are \(value)")//Gives you contains of subarray
            }
        }

    }
}

答案 2 :(得分:0)

struct ParsePlist {
    let plistName:String

    init(name:String) {
        plistName = name
    }

    func sectionArrayFromPlist() -> [[Any]]? {

        guard let plistPath = Bundle.main.path(forResource: plistName, ofType: "plist") else {
            return nil
        }

        guard let rootArray = NSArray(contentsOfFile: plistPath) as? [Any] else {
            return nil
        }

        var sectionArray:[[Any]]?
        sectionArray = rootArray.flatMap({ $0 as? [Any]})
        return sectionArray
    }
}

使用:

let parsePlist = ParsePlist(name: <yourplistname>)
if let sectionArray = parsePlist.sectionArrayFromPlist() {
   // use sectionArray
}

答案 3 :(得分:-1)

我猜你在数据结构上犯了一个错误。也许你可以试试下面的代码......

var mainGroup = [[Any]]()

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

if let myArr = myArray {
   mainGroup = myArr
}