仅当应用程序未全新安装时,无法将类型 __NSCFDictionary 的值转换为 NSData

Could not cast value of type __NSCFDictionary to NSData only when app is not fresh installed

当此代码在全新安装的应用程序上运行时,它工作得非常好。但是,当设备上没有之前保存的数据时,此功能会导致应用程序崩溃。

我收到错误 Could not cast value of type __NSCFDictionary to NSData 并且它 returns 在以下行出现线程零错误:

playlists = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(playlistsData as! Data) as! [String:[Song]]

下面是我的完整功能代码:

func getPlaylists() -> [String:[Song]] {
        var playlists: [String:[Song]] = [:]
        let playlistsData = defaults.object(forKey: "user_playlists")
        if playlistsData != nil {
            playlists = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(playlistsData as! Data) as! [String:[Song]]
        }

        return playlists
    }

第一次工作,因为 playlistsData 一开始是零

 let playlistsData = defaults.object(forKey: "user_playlists")

  >>>>>>   hereis the crash  >>>>> playlistsData as! Data

您应该将对象存储在 Data 中而不是 Dictionary

guard let data = try? NSKeyedArchiver.archivedData(withRootObject: somethingToSave, requiringSecureCoding: false) else { return }
defaults.set(data,forKey:"user_playlists")

要安全获取数据,请将方法更改为

func getPlaylists() -> [String:[Song]] {
    guard let playlistsData = defaults.data(forKey: "user_playlists"),
          let playlists = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(playlistsData) as? [String:[Song]] else { return [:] }
    return playlists
}

顺便说一下,错误的发生是因为您之前将字典保存到 UserDefaults 而不是 Data

您的意思可能是但是,当之前保存的数据时...