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 Thank you for an excellent post on this topic! I’ve seen the same issue even though I store my settings in a file. I’m a bit hesitant to disable encryption for my use-case. What do you think of moving the initialization code (that depends on the settings file) from init to applicationWillFinishLaunching?
@mhalttu That area still isn't safe, nor is didFinishLaunching. Why are you worried? You shouldn't be storing anything sensitive in there, and even if you are, it's decrypted the first time the user unlocks their device after reboot, if they lock it again it's still decrypted
@christianselig may I ask why do you say that method is not safe? According to https://developer.apple.com/documentation/uikit/app_and_environment/responding_to_the_launch_of_your_app/about_the_app_launch_sequence “Prewarming executes an app’s launch sequence up until, but not including, when main() calls UIApplicationMain(_:_:_:_:)” and applicationWillFinishLaunchingWithOptions happens only after that.
About the app launch sequence | Apple Developer Documentation

Learn the order in which the system executes your code at app launch time.

Apple Developer Documentation
@mhalttu See my blog post, the docs are just wrong haha
@christianselig I had missed that part. Wow. The fact that the documentation has been wrong for years blows my mind. Thanks again!
@mhalttu Mine too haha. No problem!