swiftnsuserdefaultsuserdefaultssuite

How to delete all userdefaults data of only one subproject?


My project have several subprojects inside main project. I’d like to remove all userdefaults datas in only one subproject. I searched and found ‘suite’ concept in userdefaults, but looks like that suite is mostly used for app groups. Since I don’t need to share datas between app groups, I don’t know whether ‘suite’ is the best way or not. Is there any other good way to delete userdefaults data of only one subproject?


Solution

  • you can use enums to declare your keys for your subproject and conform it by caseiterable protocol and in for loop you can remove them. I've added the example below

    var unqKey = "some unique ID" //EDIT
    
    enum SubProjectKeys  : String,CaseIterable{
    
        case key1
        case key2
        case key3
        case key4
    
        var uniqueKey : String { //EDIT
    
                return  unqKey + self.rawValue
            }
    
    
    
    }
    
    
    func removeKeysForSubProject() {
    
        let userDefaultsObj = UserDefaults()
        for key in SubProjectKeys.allCases {
    
            userDefaultsObj.removeObject(forKey:  key.uniqueKey) //EDIT
            userDefaultsObj.synchronize()
        }
    }