gpt4 book ai didi

swift - "Value for key ' root ' was unexpected class ' NSArray '"在 UserDefault, Swift 中检索对象数组时出错

转载 作者:行者123 更新时间:2023-12-04 12:42:49 24 4
gpt4 key购买 nike

我正在尝试在 Swift 中检索一组自定义对象,但出现错误

"UserInfo={NSDebugDescription=value for key 'root' was of unexpected class 'NSArray'. Allowed classes are '{(MusicCloud.Playlist)}"

我的项目是一个音乐播放器,所以我有一个 Song 对象和一个 Playlist 对象,它们将有一个名称和列表歌曲。

我已经对对象模型进行了编码:
class Playlist: NSObject, NSCoding{
var name: String
var songs: [Song]
var image: UIImage

override init() {
self.name = ""
self.songs = []
self.image = UIImage()
}

init(name: String, songs: [Song], image: UIImage) {
self.name = name
self.songs = songs
self.image = image
}

required convenience init(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: "name") as! String
let songs = aDecoder.decodeObject(forKey: "songs") as! [Song]
let image = aDecoder.decodeObject(forKey: "photo") as! UIImage
self.init(name: name, songs: songs, image: image)
}

func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(songs, forKey: "songs")
aCoder.encode(image, forKey: "photo")
}
}

存储播放列表:
let playlist: Playlist = Playlist(name: txt.text!, songs: [], image: UIImage())
MusicService.shared.playlists.append(playlist)
do{
let encodedData: Data = try NSKeyedArchiver.archivedData(withRootObject: MusicService.shared.playlists, requiringSecureCoding: false)
self.userDefaults.set(encodedData, forKey: "playlist")
self.userDefaults.synchronize()
}catch let error{
print("error when add \(error)")
}

并检索它:
do{
let decodedPlaylists = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [Playlist.self], from: decoded!) as! [Playlist]
print("here is decoded playlist: \(decodedPlaylists)")
MusicService.shared.playlists = decodedPlaylists
}catch let error{
print("error when retrieve \(error)")
}

完整的错误描述:
Domain=NSCocoaErrorDomain Code=4864 "value for key 'root' was of unexpected class 'NSArray'. Allowed classes are '{(
MusicCloud.Playlist
)}'."

如果我遗漏了什么,任何人都可以告诉我。非常感谢!

最佳答案

我不知道为什么但从

let decodedPlaylists = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [Playlist.self], from: decoded!) as! [Playlist]


let decodedPlaylists = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decoded!) as! [Playlist]

将为我解决问题。所以我会在这里关闭我的票。如果你注意到了,谢谢!

关于swift - "Value for key ' root ' was unexpected class ' NSArray '"在 UserDefault, Swift 中检索对象数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217216/

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