我正在解析数据并实例化每个Time根元素(objstation)的结构并编码为DATA以写入plist
XML结构
<objStation>
<StationDesc>Killester</StationDesc>
<StationAlias/>
<StationLatitude>53.373</StationLatitude>
<StationLongitude>-6.20442</StationLongitude>
<StationCode>KLSTR</StationCode>
<StationId>101</StationId>
</objStation>
<objStation>
<StationDesc>Clontarf Road</StationDesc>
<StationAlias/>
<StationLatitude>53.3629</StationLatitude>
<StationLongitude>-6.22753</StationLongitude>
<StationCode>CTARF</StationCode>
<StationId>109</StationId>
</objStation>
我在结构中使用以下方法进行编码并写入plist,但是仅将结构的当前实例保存到plist,我想知道如何追加到plist,因此将所有根元素保存到在plist中,我在DATA类型周围玩过各种快速的本机函数,但并不开心。 也许我应该为此使用一个字典数组而不是一个结构?
//mark properties, update as necssary, based on xml strucutre
struct StationsEncoder: Codable {
var station: String
var latitude: String
var longitude: String
var code: String
var id: String
//MARK: Initialization
init(station: String, latitude: String, longitude: String, code: String, id: String ) {
self.station = station
self.latitude = latitude
self.longitude = longitude
self.code = code
self.id = id
}
//mark initializers
// lets try encode our data
func encoder(){
let stationStruct = StationsEncoder(station: station, latitude: latitude, longitude: longitude, code: code, id: id)
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
do {
let data = try encoder.encode(stationStruct)
try data.write(to: CreatePlist.shared.plistURL)
} catch {
// Handle error
print(error)
print( CreatePlist.shared.plistURL)
}
}
}
答案 0 :(得分:0)
我使用PropertyListSerialization
方法用少量代码完成了这一点(再次感谢Maddy节省了时间,指出您不能将其附加到plist上)。我发现最好的选择是先添加到字典,然后将整个字典写出到plist:
do {
let writeData = try PropertyListSerialization.data(fromPropertyList: [parsedDictionary], format: .xml, options:0)
//note CreatePlist.shared.plistURL is my URL, just replace with yours, I am accessing a singleton class that has the URL here for convenience:
try writeData.write(to: CreatePlist.shared.plistURL)
} catch {
print(error)
}