Writing user.defaults slow?

I don't know if I'm imagining things, but testing my code right now I find that the culprit could be user.defaults doesn't write fast enough?

I find that it takes around three to five seconds for the write to reliably work, which is odd as I recall the information at the time it will display correctly as having been changed, but resetting the simulator the data hasn't, if I do it one second after for example.

I take it then that NSUserDefaultsDidChangeNotification would be useless as the data will show as having been saved, while in practice if I rebuild the code on the simulator it will not have had time to save.

In normal use this would not be a problem, but testing takes so much time I wanted to speed things up and it's been driving me mad as I know my code to be sound. I know that Plists take time to work, so I think it's just the speed ?

The doc say:

When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.

the actual persist is done asynchronously, how fast that's carried out? Who knows? But it doesn't matter because even if the app is killed, it should have 10s before it die. So your UserDefaults write should have time to flush. I say 10s because that's how much time iOS give the app when it notify the app of enter .background.

If you run the app from Xcode, it disable the WatchDog task, so your app doesn't get killed. So there should be time for UserDefaults write.

It's common to use the synchronize() api to force it to persist after doing your writes. It's possible that it may not persist if you do a write, and even a synchronize while the app is being shut down.


this method is unnecessary and shouldn't be used


[former NSUserDefaults maintainer hat on]

Yeah, on modern OSs, it should be essentially instant to get it to "safely out of your process". Synchronize does almost literally nothing now. If you're seeing it take a long time you may have some other bug that's confusing things, or you could be running into a bug in the OS (please file it and attach a sysdiagnose taken immediately after reproducing the issue if so!), but it's not expected behavior anymore.

1 Like

Hi guys, and thanks for the help. I found that I was quitting out just too quickly, and we're talking almost as soon as the request was made of the Default, but waiting a few seconds was all I needed.

If it's an iOS app, then this doesn't sound right: your app is not killed immediately. It should have time to flush user default write.

If it's macOS, then I don't know.

It's iOS, but the SKScene I was on changed too quickly, I know this because if I spend more time on it then the data saved.

Something unusual is going on here then. The required wait time should be shorter than human reaction times.

Terms of Service

Privacy Policy

Cookie Policy