Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40226

How to remove all data by a suite name from UserDefaults in Swift?

I have created user defaults with names below,

let prefs1 = UserDefaults.init(suiteName: "UserAccount")
let prefs2 = UserDefaults.init(suiteName: "UserInfo")

Then I have added some values to those suites. i.e.

prefs1.set(true, forKey: "Key1")
prefs1.set(true, forKey: "Key2")

prefs2.set(false, forKey: "Key1")
prefs2.set(false, forKey: "Key2")

Now, I want to remove the prefs1 (i.e. name "UserAccount"), but not prefs2. I tried,

UserDefaults.standard.removePersistentDomain(forName: "UserAccount")

But it did not remove. I am getting confused with, forName and suiteName

How to remove a suite from UserDefaults keeping other suites intact in Swift?

Upvotes: 3

Views: 4861

Answers (3)

Michael Ozeryansky
Michael Ozeryansky

Reputation: 8053

func removePersistentDomain(forName domainName: String)

https://developer.apple.com/documentation/foundation/userdefaults/1417339-removepersistentdomain

Calling this method is equivalent to initializing a user defaults object with init(suiteName:) passing domainName, and calling the removeObject(forKey:) method on each of its keys.

Upvotes: 6

ingconti
ingconti

Reputation: 11646

I usually a different approach that also cleans up keys, based in idea "nil = no more exisiting":

// make property:

   var userName: String? {

        set(NewValue) {
            self.setUserDefault(value: NewValue, for: USERNAME_KEY)
        }
        get{
            let v =  self.getFromUserDefaultsWith(key: USERNAME_KEY) as? String
            return v
        }
    }

// accessory functions: (here the trick)

private final func getFromUserDefaultsWith(key: String) -> Any? {
    let returnValue  = UserDefaults.standard.object( forKey: key)
    return returnValue
}

private final func setUserDefault(value: Any?, for key: String) {
    let ud = UserDefaults.standard
    if value == nil{
        ud.removeObject(forKey: key)
    }else{
        ud.set(value, forKey:  key)
    }
    ud.synchronize()
}

SO I can write:

final func wipeOut() {
    // if nil, we remove... see above.
    self.setUserDefault(value: nil, for: USERNAME_KEY)
}

Upvotes: -1

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

You can try

UserDefaults.standard.removeSuite(named: "UserAccount")

If you want to just remove the keys. You can go for following

func removeAllFor(defaults: UserDefaults) {
        let dictionary = defaults.dictionaryRepresentation()
        dictionary.keys.forEach { key in
            defaults.removeObject(forKey: key)
        }
    }

Then you can call it on default that you want to clear data for

removeAllFor(defaults: prefs1)

removeSuite(named:) : Removes a sub-searchlist added via -addSuiteNamed method

removePersistentDomain(forName: ) : Removes all values from the search list entry specified by ‘domainName’.

Upvotes: 2

Related Questions