Saving a dictionary object to a dictionary to disk

Hi,


Im looking for the best option for simple data archiving. I want the user to be able to save CLCoorinates with a string and then later be able to retrieve this. There will be multiple entries but no more than a dozen. Is it better to save this data inside a dictionary first then save the dictionary to disk? And would NSArchiver the way to go here? Im a total noobie when it comes to archiving defaults and simple data, any data for that matter.


kind regards

Replies

I’m looking for the best option for simple data archiving.

Are you working in Swift or Objective-C?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Sorry for the late reply - Swift.

If you’re working in Swift your best option for simple persistence is

Codable
. So something like this:
struct Location : Codable {
    var latitude: Double
    var longitude: Double
    var title: String
}

func save(to url: URL) throws {
    let loc = Location(latitude: 0.0, longitude: 0.0, title: "middle of nowhere")
    let data = try! JSONEncoder().encode(loc)
    try data.write(to: url)
}

If you dump the data on line 9 you’ll find it looks like this:

{"title":"middle of nowhere","longitude":0,"latitude":0}

which is a pretty reasonable way to archive your data.

Note that if you prefer property lists over JSON you can use

PropertyListEncoder
.

To learn more, check out Encoding and Decoding Custom Types.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Cool thanks, I checked out the documentation.

One question - the url part. What is the url that goes in there if saving to the device?


Thanks again.

What is the url that goes in there if saving to the device?

That depends on the details of your app. For a very simple iOS app that just wants to save one set of state, you can use a URL relative to the Documents directory. For example:

let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let saveFile = docDir.appendingPathComponent("MySaveFile.json")

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"