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

前端 未结 3 860
陌清茗
陌清茗 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: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)
    }
    

提交回复
热议问题