将数组添加到plist(我的plist上只能看到一个项目)

时间:2018-04-26 08:09:02

标签: plist codable saving-data

import Foundation

struct answers : Codable {
    var answer : String
    var number : Int
}

var allAnswers: Array = [answers]()

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let archiveURL = documentsDirectory.appendingPathExtension("answers_test").appendingPathExtension("plist")

class ViewController: UIViewController {

    @IBOutlet var vcLabels: [UILabel]!
    @IBOutlet weak var vcTextField: UITextField!
    var index : Int = 0
    @IBAction func vcButtonPressed(_ sender: Any) {
       vcLabels[index].text =  vcTextField.text
      var newAnswer = answers(answer: vcLabels[index].text!, number: index)

        var newAnswers = [newAnswer]
       print(archiveURL)
        index += 1

        if index == 4 {
            index = 0
        }

        let propertyListEncoder = PropertyListEncoder()
        let encodedNotes = try? propertyListEncoder.encode(newAnswers)
        try? encodedNotes?.write(to:archiveURL, options: .noFileProtection)


    }

1 个答案:

答案 0 :(得分:0)

首先,请遵循结构和类名以大写字母开头的命名约定,结构Answer和属性answer不能错误的好处。并且为了避免更多的混淆,以单数形式命名结构(在创建新答案的行中,您创建语义一个答案,而不是一个答案)。并且属性可以声明为常量(let)。

struct Answer : Codable {
    let answer : String
    let number : Int
}

您的问题非常明确:如果您要在属性列表文件中附加内容,则必须先从archiveURL 读取,然后附加项目并将其写回

@IBAction func vcButtonPressed(_ sender: Any) {
    vcLabels[index].text =  vcTextField.text
    let newAnswer = Answer(answer: vcLabels[index].text!, number: index)
    print(archiveURL)
    index += 1

    if index == 4 {
        index = 0
    }

    do {
        let data = try Data(contentsOf: archiveURL)
        var savedAnswers = PropertyListDecoder().decode([answers], from: data)
        savedAnswers.append(newAnswer)

        let encodedNotes = try PropertyListEncoder().encode(savedAnswers)
        try encodedNotes?.write(to:archiveURL, options: .noFileProtection)
    } catch { print(error) }

}

并且不要忽略try?的错误。 处理它们