Chapter 16, P292: NSKeyedUnarchiver.unarchivedObject

Hi all,

I am referring to the following textbook reference:

init() {
if let archivedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemArchiveURL.path) as? [Item] {
allItems = archivedItems

I am getting an error message in XCODE as this method is now obsolete. Can someone please assist in what new commands I need to enter in order to successfully restore the Items in this example of the book?

It seems that saving data I have managed to achieve, but retrieving the data is impossible.

Please Help as am new to iOS programming!

Best Regards,


According to the documentation, that function has been superseded by the following functions.

class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any?

static func unarchivedObject<DecodedObjectType>(ofClass cls: DecodedObjectType.Type, from data: Data) throws -> DecodedObjectType? where DecodedObjectType : NSObject, DecodedObjectType : NSCoding

static func unarchivedObject(ofClasses classes: [AnyClass], from data: Data) throws -> Any?

Use one of them. To use one, you need to create a data object from the archive file first.

Thank you ibex10, can you please show me how to rewrite the code in order to make the book program functional? I have tried but with no success.

init() {
    if let data = try? Data(contentsOf: itemArchiveURL) {
        if let archivedData = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [Item] {
            allItems = archivedData ?? [Item]()

This worked for me. I’m still a novice so there are probably better ways to do it.