Help with NSKeyedUnarchiver NSKeyedArciver

I finnished a course that used

let unarchivedData = UserDefaults.standard.object(forKey: key) as ? NSData
return NSKeyedUnarchiver.unarchivedObject(with: unarchivedData) as? [[Task]]

And

return NSKeyedUnarchiver.archivedData(withRootObject: tasks) as NSData

THey don't seem to work anymore, how should they be written instead

Consider:

  • Please post the actual error your got, because it’s hard to diagnose an error when without actually seeing it.

  • Please format your code as code blocks (use the </> icon in the editor), because that’ll make your posts easier to read.

  • Do these code snippets represent your actual code? My specific concern is your second code snippet, which shows NSKeyedUnarchiver but which is obviously must be NSKeyedArchiver because that’s the only thing that makes any sense in this context. Is that a problem with your post? Or with your code? Or with the course you’re following?

  • Whatever course you’re following seems to be somewhat out of date. Specifically:

    • Most Swift projects these days use Swift’s built in Codable rather than the older NSCoding. There are circumstances where NSCoding is the right option, but if you’re just getting started then Codable is much easier.

    • The references to NSData seem weird. You should not need to bounce through NSData in this situation. For example, unarchiveObject(with:) takes a Data parameter, not an NSData.

    • It doesn’t use the latest APIs. For example, in this situation I’d use UserDefaults.data(forKey:) rather than UserDefaults.object(forKey:).

    • It doesn’t use NSSecureCoding, which is strongly recommended in modern code. For more background on this, see WWDC 2018 Session 222 Data You Can Trust.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

Thank you. I "found" in xcode, that I can use an older version of swift. That solved the problem of making the app run. Other than that, you gave me some helpful pointers on how to proceed when continuing the app.

Terms of Service

Privacy Policy

Cookie Policy