我正在尝试在Swift中检索自定义对象数组,但遇到错误。
"UserInfo={NSDebugDescription=value for key 'root' was of unexpected class 'NSArray'. Allowed classes are '{(MusicCloud.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
)}'."
请问有人能告诉我是否有遗漏的地方吗?非常感谢!
NSCoding
,而应该使用Codable
。 - Dávid PásztorNSCoding
是将自定义对象保存到文件系统的传统方式,而Codable
是一种新的、纯Swift的解决方案,更加类型安全,因此您应该使用它来替代传统的解决方案。 - Dávid Pásztor