Search code examples
iosswiftnsuserdefaults

Save an Object into User Defaults


I am not able to save the list of viewControllers in my user defaults, its getting crashed at this userDefault.set(vcList, forKey: "vcList").

The error log says:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object

import UIKit

class ViewController: UIViewController {

    struct viewControllerList {
        var vc1 = ViewController()
        var vc2 = LoginViewController()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let vcList = viewControllerList()
        let userDefault = UserDefaults.standard
        userDefault.set(vcList, forKey: "vcList")
    }
}

Please help!


Solution

  • The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.

    A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.