unarchiveObject(with:) deprecated, is there a replacement when you are unwinding NOT a class but a vanilla [String: Any?]
Asked Answered
C

0

0
req = ["a":nil, "b":3, "c":["d":3.3, "e":"e", "f":[]], "g":[]]

Traditionally ("if js can do it we can do it too!") if you wanted to just throw any old object in storage you would ...

req: [String: Any?] ... typical api package or whatever
let enc: Data = try! NSKeyedArchiver.archivedData(
                              withRootObject: req, requiringSecureCoding: false)
eg, UserDefaults.standard.set(enc, forKey: "data_rqst")

and then out

let enc: Data = UserDefaults.standard.object(forKey: "data_rqst") as? Data,
let rec = NSKeyedUnarchiver.unarchiveObject(with: enc) as? [String: Any?],

Sadly these days,

'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead

enter image description here

Is there a replacement which allows you to [String: Any?] ?

Unfortunately solutions and mentions I've found are when you have a codable class.

I was surprised to see (unless I have the syntax wrong) you apparently cannot simply use something like [String: Any?]? with .self as the class in unarchivedObjectOfClass#fromData (or "classes") calls.

Circulation answered 1/7 at 18:51 Comment(6)
How about creating an enum with associated values to represent all the possible things the data can contain? See this answer that does this for JSON. If you really don't want to be type-safe for some reason, do something like this answer, which produces a [String: Any] directly.Subterranean
It's such a shame - they seem to be literally taking away the ability to decode a free, nested, dictionary - sad!Circulation
(I added an example request up top of the question.) You know what I believe the second approach fails anyway with nesting/optional like that @Subterranean . I was surprised to see (unless I have the syntax wrong) you can't simply use something like [String: Any?]? with .self as the class in unarchivedObjectOfClass#fromData (or "classes") calls. Ah well.Circulation
try let enc = UserDefaults.standard.data(forKey: "data_rqst")!; let unarchiver = try! NSKeyedUnarchiver(forReadingFrom: enc); unarchiver.requiresSecureCoding = false; let rec = try! unarchiver.decodeTopLevelObject(of: [NSDictionary.self, NSString.self, NSNumber.self, NSArray.self, NSNull.self], forKey: NSKeyedArchiveRootObjectKey) as! [String: Any?]; print(rec); Supersensitive
my goodness! @Supersensitive I think that sort of works!! - however - I think it might not do nested? its a bit confusing and takes some time to test .. a test is req = ["a":nil, "b":3, "c":["d":3.3, "e":"e", "f":[]], "g":[]]Circulation
@Circulation sorry, i can't help. (pretty sure it can be solved but i don't have enough motivation to keep trying)Supersensitive

© 2022 - 2024 — McMap. All rights reserved.