如何将一组自定义结构保存为plift swift

时间:2015-11-10 18:52:53

标签: ios arrays swift plist

我试图将警报数据保存到一个plist,它是一个类alertli数组的形式,我可以找到指向编码它的所有信息,然后将它放入数组中,但是我对此有何疑惑?我也无法弄清楚如何去做,这是我的游乐场:任何帮助都会很棒

班级(我试图保存这些数组)

public class alertData: NSObject, NSCoding {
//Properties of the timer data - make optionals optional i.e. alert count etc.

var alertCounter: NSTimeInterval?
var alertText: String?
var alertColor: UIColor?
var alertColorIndex: Int?


//initialisation
init(alertCounter: Double, alertText: String, alertColor: UIColor, alertColourIndex: Int) {

    self.alertCounter = alertCounter
    self.alertText = alertText
    self.alertColor = alertColor
    self.alertColorIndex = alertColourIndex
}

public required init(coder aDecoder: NSCoder) {
    alertCounter = aDecoder.decodeDoubleForKey("Item1")
    alertText = aDecoder.decodeObjectForKey("Item2") as? String
    alertColor = aDecoder.decodeObjectForKey("Item3") as? UIColor
    alertColorIndex = aDecoder.decodeIntegerForKey("Item4")
}

public func encodeWithCoder(aCoder: NSCoder) {
    alertCounter = aCoder.decodeDoubleForKey("Item1")
    alertText = aCoder.decodeObjectForKey("Item2") as? String
    alertColor = aCoder.decodeObjectForKey("Item3") as? UIColor
    alertColorIndex = aCoder.decodeIntegerForKey("Item4")
}
}

数组(当我在应用程序中添加警报数据时会填充):

var alertDataSource: [alertData] = []

并对其进行编码:

let archive = NSKeyedArchiver.archivedDataWithRootObject(self.alertDataSource)
            print(archive)

并提取它:

let result = NSKeyedUnarchiver.unarchiveObjectWithData(archive)
            print(result)

提前感谢任何提示/建议

1 个答案:

答案 0 :(得分:1)

您并不打算自己致电encodeWithCoder()。使用NSKeyedArchiverNSKeyedUnarchiver。归档器/ unarchiver将根据需要调用init(coder:)encodeWithCoder()

将您的NSCoding - 兼容的alertData实例(这应该是AlertData,因为类名应该是正确的情况)放入数组(或字典,如果您愿意)并执行此操作:

let archive = NSKeyedArchiver.archivedDataWithRootObject(yourArrayOfAlertData)

在这种情况下,archive将是NSData个实例。

<强>更新

实际上,我想我第一次错过了,但你的encode...()方法并不正确。完全没有。考虑与以下区别:

public func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeDouble(alertCounter, forKey:"Item1")
    aCoder.encodeObject(alertText, forKey:"Item2")
    aCoder.encodeObject(alertColor , forKey:"Item3")
    aCoder.encodeInteger(alertColorIndex, forKey:"Item4")
}

(另请考虑将您的密钥命名为与其属性相同,例如"alertCounter" alertCounter