在UserDefault,Swift中检索对象数组时出现“键'root'的值是意外类'NSArray'”的错误

时间:2019-05-20 08:42:15

标签: swift nsobject nscoding userdefaults

我正在尝试在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
)}'."

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

2 个答案:

答案 0 :(得分:0)

我不知道为什么,但是从

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

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

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

答案 1 :(得分:0)

尝试

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

我猜,

以下解码代码包含NSArray

的数据结构
let songs = aDecoder.decodeObject(forKey: "songs") as! [Song]