SafeMode in UserDefaults
UserDefaults is a built-in Utility included in Foundation. It allows Developers to save User’s settings with one line call.
NSUserDefaults has a list of places to look for data called the “search list”. A search list is referred to by an arbitrary string called the “suite identifier” or “domain identifier”. When queried, NSUserDefaults checks each entry of its search list until it finds one that contains the key in question, or has searched the whole list. (Apple)
Basically, It performs perfectly for most of the cases. But let imagine that you are 2 peoples working on the same project, which will use the same UserDefaults instance. And one day, your friend accidentally overrides your settings, which makes your feature turn into unexpected behavior.
I think it’s better if we can use UserDefaults in a concerned, be awarded way. Like if we want to save an item into UserDefaults, we want to make sure that if won’t be overridden without our very-sure permission.
So I wrote a Swift Package called SafeModeUserDefaults :), like this:
The mechanism is before saving Item to UserDefaults, it will ask back in case need permission to override, that’s it, very simple.
For more use-cases, you can check the Document in the Package.
If you find it’s helpful for you, try it.
If you find any bug or suggestions, please feel free to create a PR or raise an issue, I will look into it and fix it.
In the next steps, I would like to apply the same mechanism for another storage like Keychains.
Thanks for reading!