gpt4 book ai didi

ios - 将数据类型附加到 Plist

转载 作者:行者123 更新时间:2023-11-30 11:01:49 28 4
gpt4 key购买 nike

每次根元素(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 类型的各种快速 native 函数,但没有任何乐趣。也许我应该使用字典数组而不是结构体?

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


}

最佳答案

我使用 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)
}

关于ios - 将数据类型附加到 Plist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53290650/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com