Home > Mobile >  Ability to determine whether a custom suite of UserDefault exists, enabling custom behaviour when it
Ability to determine whether a custom suite of UserDefault exists, enabling custom behaviour when it

Time:03-09

I’m creating a custom suite for UserDefaults:

var store = UserDefaults(suiteName: "custom")

I however need to trigger specific behaviour based on whether the suite already exists or not.

To be specific, if the suite is not found, I want it to be initialised with preset key/value pairs. And if it was found, no special action needs to be taken. In a real-world scenario, imagine an app that initially launches with preset filters that you can individually delete (i.e. subsequent launches refers to the latest state of filters, as opposed to falling back on presets).

I know I could check for an empty state by checking for each preset’s availability, for example:

var found = 0
for key in presetKeys {
    if let _ = UserDefaults(suiteName: "custom")?.object(forKey: key) {
        found  = 1
    }
}

if found == 0 {
    // empty suite
}

However, this isn’t helpful, as an empty state doesn’t indicate a first run. It could be because the user deleted all the presets they were automatically assigned. Furthermore, users can create their own key/value pairs to add into the suite. Their keys are dynamically generated ruling out an empty state check then (because I wouldn’t know what keys to look for).

To conclude, is there a way I can simply tell if a suite by a specified name already exists?

If yes, does the suite continue to exist even when all its key/value pairs were removed? I wouldn’t want a scenario whereby a user-triggered empty state results in the suite being permanently removed, therefore causing the next run of the app to automatically reload the presets because it’s mixing up an empty v new state.

Hope this makes sense!

CodePudding user response:

There's no built-in way to check if a specific UserDefaults suite already exists.

However, you can create a special key with a Bool value, which you use as a flag for whether any of the preset values were modified.

does the suite continue to exist even when all its key/value pairs were removed?

Yes. A UserDefaults suite does not need to hold any values, it can be empty. Deleting all values from a suite does not affect the existence of the suite itself.

  • Related