Is it common to convert object to json string and save it to UserDefaults

To save an Object to UserDefaults, the most common proposed way is using

let teams = [Team(id: 1, name: "team1", shortname: "t1"), Team(id: 2, name: "team2", shortname: "t2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")
userDefaults.synchronize()

But, I was wondering, is it Ok for us, to convert the Object to json String, and then save it to UserDefaults as String?

As, I seldom see Object to json String, as the proposed method to save Object to UserDefaults. Thought there might be a catch?

Thank you.

You can save it as a String, but then you are just going to need to parse it when you load it. Unless it really needs to be JSON I would probably just convert it to one of the property list types and then use it in my code like that.

Also synchronize() doesn't actually do anything anymore. I think it's only hung around to prevent old stuff from breaking.

I sometimes do it.

The things I've found to keep in mind is that UserDefaults are meant for small, fully replaceable data. Don't try and use it as a database or file system. If it's a large structure or something where you'll need to update, (not replace), the Model schema you're better of using other solutions.

Unfortunately that's not always easy to do. The Types allowed in a P-List are relatively constrained, it adds an additional serialization format you have to support/test, it's also larger and less portable than JSON.

1 Like

Absolutely true. I think a lot of people start out using it because it's convenient, but then it gets out of control pretty quickly.

Right? It's easier to deal with than the file-system or a full database so it tends to be my quick-and-dirty way to save data when starting something. Which is fine...until it isn't. :innocent:

As an aside, in my brief benchmarking, using JSON as the data storage for UserDefaults values was both faster and slightly smaller than property lists.

I've benchmarked the same way back when on slow iOS hardware, but the ability to use JSON as the format is so briefly documented I was always worried it might go away.

plutil lists JSON as as a valid file format and as a valid key value type, but I've not seen it in the defaults documentation.

No, I mean pure JSON, not JSON plist format, which isn’t accessible programmatically AFAIK.

If it doesn't cause you any performance issues (because your are storing a lot of data this way) then it's perfectly fine. I used this a couple years ago as it has a 1 liner API: https://github.com/Nirma/Default