BLACK FRIDAY: Save 50% on my Swift books and videos! >>

How to save and load objects with NSKeyedArchiver and NSKeyedUnarchiver

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 fullPath = getDocumentsDirectory().appendingPathComponent(randomFilename)

do {
    let data = try NSKeyedArchiver.archivedData(withRootObject: somethingToSave, requiringSecureCoding: false)
    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:

do {
    if let loadedStrings = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [String] {
        savedArray = loadedStrings
    }
} catch {
    print("Couldn't read file.")
}

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.

Need to know Objective-C fast?

I wrote a book dedicated to teaching Objective-C to developers who already know Swift – it's the fastest way to get up to speed!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>