Beware UserDefaults: a tale of hard to find bugs, and lost data https://christianselig.com/2024/10/beware-userdefaults/
Beware UserDefaults: a tale of hard to find bugs, and lost data

Excuse the alarmist title, but I think it’s justified, as it’s an issue that’s caused me a ton of pain in both support emails and actually tracking it down, so I want to make others aware of it so they don’t similarly burned. Brief intro For the uninitiated, UserDefaults (née NSUserDefaults) is the de facto iOS standard for persisting non-sensitive, non-massive data to “disk” (AKA offline). In other words, are you storing some user preferences, maybe your user’s favorite ice cream flavors? UserDefaults is great, and used extensively from virtually every iOS app to Apple sample code. Large amount of data, or sensitive data? Look elsewhere! This is as opposed to just storing it in memory where if the user restarts the app all the data is wiped out.

@christianselig good too know about this problem, but about your solution, wouldn’t be better to use an actor instead of a queue? Using sync may lock the thread anyway right?
@Robuske It would lock a background thread only enough to perform minor file IO, shouldn't be noticeable. I swear I remember reading actors weren't recommended for file IO nor do I believe they guarantee any form of serial execution

@christianselig they do guarantee serial execution by nature of how they work
“only one task to access their mutable state at a time”

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Actors

That said, am still learning the new concurrency system, so I don’t know about they being bad for IO, what I have seen is that it might be a better idea to use @‘MainActor instead of really creating an actor since a lot of Apples APIs need to be run on the main thread

Documentation

@christianselig I have read my answer again and realized that it is actually only guaranteeing one access, not that it would be in the same order, I think I read that somewhere, but is not present in that part of the documentation 🤔
@Robuske Ah found it. Yeah there’s some interesting discussion in here about that problem https://forums.swift.org/t/actors-that-serialise-file-access/66652
Actors that serialise file access

Technically speaking even that is not guaranteed. Swifts actors are just not FIFO today. If a high priority task arrives and others are normal, it may get to execute before the others. It was designed this way, in order to facilitate serving those high priority work as soon as possible. And even allowing an “skip the work, we no longer need it!” Messages to jump in front of the queue etc… But yes, it means we just don’t — in the general sense of the word — have FIFO in actors today. If all y...

Swift Forums