How to convert custom array to NSData in swift?

I am trying to save NSUserDefaults data. Here is my code

  @IBAction func saveBtn(sender: AnyObject) { var userName = nameLbl.text UserInfo.append(User(name: userName)) NSUserDefaults.standardUserDefaults().setObject(UserInfo, forKey: "UserInfo") userName = "" } 

But when I click the "Save" button, it shows Attempt to set a non-property-list object . I think UserInfo array needs to be converted as NSData . Please tell me how can I do this?

0
source share
1 answer

You need your user object to comply with the NSCoding protocol and implement encoding and decoding methods. Once you do this, you can use the encode method to create an NSData object for use with NSUserDefaults.

Something like this in your UserInfo class:

 required convenience init?(coder decoder: NSCoder) { self.init() guard let title = decoder.decodeObjectForKey("title") as? String else {return nil } self.title = title } func encodeWithCoder(coder: NSCoder) { coder.encodeObject(self.title, forKey: "title") } 

Then you can use the encoded data using NSUserDefaults as follows:

 @IBAction func saveBtn(sender: AnyObject) { var userName = nameLbl.text UserInfo.append(User(name: userName)) let data = NSKeyedArchiver.archivedDataWithRootObject(UserInfo) NSUserDefaults.standardUserDefaults().setObject(data, forKey: "UserInfo") userName = "" } 
0
source

Source: https://habr.com/ru/post/1236318/


All Articles