gpt4 book ai didi

swift - 保存数组 [String : Any] to user default crash occasionally?

转载 作者:行者123 更新时间:2023-11-30 12:27:23 25 4
gpt4 key购买 nike

我尝试将 [String: Any] 数组保存为用户默认值,在某些情况下它可以工作,但在其他情况下则不行。我使用以下内容保存为默认值:

 static func savingQueueToDisk(){
let queueDict = App.delegate?.queue?.map({ (track) -> [String: Any] in
return track.dict
})

if let queueDict = queueDict{
UserDefaults.standard.set(queueDict, forKey: App.UserDefaultKey.queue)
UserDefaults.standard.synchronize()
}
}

Queue是Track的数组,其定义如下:

class Track {

var dict: [String: Any]!

init(dict: [String: Any]) {
self.dict = dict
}

var album: Album?{
guard let albumDict = self.dict[AlbumKey] as? [String: Any] else{
return nil
}
return Album(dict: albumDict)
}

var artists: [Artist]?{
guard let artistsDict = self.dict[ArtistsKey] as? [[String: Any]] else{
return nil
}
let artists = artistsDict.map { (artistdict) -> Artist in
return Artist(dict: artistdict)
}
return artists
}


var id: String!{
return self.dict[IdKey] as! String
}


var name: String?{
return self.dict[NameKey] as? String
}

var uri: String?{
return self.dict[URIKey] as? String
}
}

从同一 API 检索时,我得到了不同的输出

崩溃输出: http://www.jsoneditoronline.org/?id=cb45af75a79aff64995e01e5efc0e7b6

有效输出: http://www.jsoneditoronline.org/?id=0939823a4ac261bd4cb088663c092b20

最佳答案

事实证明,直接将 [String: Any] 数组存储到用户默认值是不安全的,并且它可能会根据它包含的数据而中断,因此提示 can' t 将 none-property-list 设置为用户默认值。我通过首先使用 JSONSerialization[String: Any] 数组转换为 Data 来解决这个问题,现在它可以正确保存。

解决方案:

//saving current queue in the app delegate to disk
static func savingQueueToDisk(){
if let queue = App.delegate?.queue{
let queueDict = queue.map({ (track) -> [String: Any] in
return track.dict
})

if let data = try? JSONSerialization.data(withJSONObject: queueDict, options: []){
UserDefaults.standard.set(data, forKey: App.UserDefaultKey.queue)
UserDefaults.standard.synchronize()
}else{
print("data invalid")
}
}
}

//retriving queue form disk
static func retrivingQueueFromDisk() -> [Track]?{
if let queueData = UserDefaults.standard.value(forKey: App.UserDefaultKey.queue) as? Data{
guard let jsonObject = try? JSONSerialization.jsonObject(with: queueData, options: []) else{
return nil
}

guard let queueDicts = jsonObject as? [[String: Any]] else{
return nil
}
let tracks = queueDicts.map({ (trackDict) -> Track in
return Track(dict: trackDict)
})
return tracks
}
return nil
}

关于swift - 保存数组 [String : Any] to user default crash occasionally?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010721/

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