Unarchive Array with NSKeyedUnarchiver unarchivedObject(ofClass:from:)

后端 未结 6 2046
别跟我提以往
别跟我提以往 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:29

    You can use unarchiveTopLevelObjectWithData(_:) to unarchive the data archived by archivedData(withRootObject:requiringSecureCoding:). (I believe this is not deprecated yet.)

    But before showing some code, you should better:

    • Avoid using NSData, use Data instead

    • Avoid using try? which disposes error info useful for debugging

    • Remove all unneeded casts


    Try this:

    private static func archiveWidgetDataArray(widgetDataArray : [WidgetData]) -> Data {
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: widgetDataArray, requiringSecureCoding: false)
    
            return data
        } catch {
            fatalError("Can't encode data: \(error)")
        }
    
    }
    
    static func loadWidgetDataArray() -> [WidgetData]? {
        guard
            isKeyPresentInUserDefaults(key: USER_DEFAULTS_KEY_WIDGET_DATA), //<- Do you really need this line?
            let unarchivedObject = UserDefaults.standard.data(forKey: USER_DEFAULTS_KEY_WIDGET_DATA)
        else {
            return nil
        }
        do {
            guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(unarchivedObject) as? [WidgetData] else {
                fatalError("loadWidgetDataArray - Can't get Array")
            }
            return array
        } catch {
            fatalError("loadWidgetDataArray - Can't encode data: \(error)")
        }
    }
    

    But if you are making a new app, you should better consider using Codable.

提交回复
热议问题