UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Alright, I have no clue what I'm doing...

Forums > Swift

Hi Folks,

This is a follow on from another thread where @Obelix gave me some great direction for storing local data in an XML file. Original Post. The problem I'm running into is that most XML documentation I can find comes from Swift 4.0, is pretty old, and doesn't answer my actual problem. I've looked at HWS(+), YouTube, several Stack threads, and can not find an answer that shows me how to store variables into an XML file, or read the values out of an XML file into a local variable.

So I settled on JSON. JSON has far more documentation available for it, but again I'm running into issues trying to learn the specific implementation I'm looking for. I want a user to update a variable, atomically update that variable in the corresponding line of the JSON file, and then read that JSON file for stored values at launch. I've got the JSON in the bundle, and injected a method to create a copy of the JSON to the document directory on the app's very first launch.

Every example I've come accross shows parsing XML data into classes or structs - I don't want to do that here, I simply want to point a variable to a corresponding line in the JSON file and read/update that specific variable there.

Am I going about this all wrong, or am I just insane?

Thanks, Andy

2      

Unless the json file is huge, it is probably faster, and certainly infinitely easier, to rewrite the entire json file. Use either Instruments or a performance unit test to see how long it takes.

To rewrite only a portion of a file, you have to determine its offset in bytes. If the new data value is a different number of bytes, I believe you have to rewrite the bytes from that offset to the end of the file anyway, so you're not gaining any speed. See https://developer.apple.com/documentation/foundation/filehandle

If the data is that huge, use a different format that does allow rewriting only desired attributes, such as plist or core data.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.