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

前端 未结 3 858
陌清茗
陌清茗 2021-01-24 04:45

I have created user defaults with names below,

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


        
相关标签:
3条回答
  • 2021-01-24 05:25

    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’.

    0 讨论(0)
  • 2021-01-24 05:45

    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)
    }
    
    0 讨论(0)
  • 2021-01-24 05:51

    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.

    0 讨论(0)
提交回复
热议问题