NEW: Master Swift design patterns with my latest book! >>

How to save and load objects with NSKeyedArchiver and NSKeyedUnarchiver

Written by Paul Hudson    @twostraws

You can write any kind of object to disk as long as it supports the NSCoding protocol – which includes strings, arrays, dictionaries, UIView, UIColor and more right out of the box. To write to disk, use this:

let randomFilename = UUID().uuidString
let data = NSKeyedArchiver.archivedData(withRootObject: somethingToSave)
let fullPath = getDocumentsDirectory().appendingPathComponent(randomFilename)

do {
    try data.write(to: fullPath)
} catch {
    print("Couldn't write file")
}

That call to getDocumentsDirectory() is a small helper function I frequently use to write files to disk:

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

When you want to read your object back you need to use unarchiveObject(withFile:), but be warned: the file might not exist or might not be unarchivable, so this method returns an optional value that you need to unwrap carefully.

For example, if you want to unarchive an array of strings, you would use this code:

if let loadedStrings = NSKeyedUnarchiver.unarchiveObject(withFile: fullPath.absoluteString) as? [String] {
    savedArray = loadedStrings
}

Available from iOS 2.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Upgrade to premium

The Hacking with Swift guide book helps you learn faster, plus get an Xcode tips and tricks video and Swift wall chart.

Click here to visit the Hacking with Swift store >>