Unarchive Array with NSKeyedUnarchiver unarchivedObject(ofClass:from:)

后端 未结 6 2054
别跟我提以往
别跟我提以往 2020-12-03 10:58

Since upgrading to Swift 4.2 I\'ve found that many of the NSKeyedUnarchiver and NSKeyedArchiver methods have been deprecated and we must now use the type method static

6条回答
  •  被撕碎了的回忆
    2020-12-03 11:25

     if #available(iOS 12.0, *) {
            guard let unarchivedFavorites = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(favoritesData!)
                else {
                    return
            }
            self.channelFavorites = unarchivedFavorites as! [ChannelFavorite]
        } else {
            if let unarchivedFavorites = NSKeyedUnarchiver.unarchiveObject(with: favoritesData!) as? [ChannelFavorite] {
                self.channelFavorites = unarchivedFavorites
            }
    

    // Achieving data

     if #available(iOS 12.0, *) {
                // use iOS 12-only feature
                do {
                    let data = try NSKeyedArchiver.archivedData(withRootObject: channelFavorites, requiringSecureCoding: false)
                    UserDefaults.standard.set(data, forKey: "channelFavorites")
                } catch {
                    return
                }
            } else {
                // handle older versions
                let data = NSKeyedArchiver.archivedData(withRootObject: channelFavorites)
                UserDefaults.standard.set(data, forKey: "channelFavorites")
            }
    

    This is the way I have updated my code and its working for me

提交回复
热议问题