1

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?

  • In my subproject, there are 20~30 userdefaults datas. So,I think it’s inconvenient way if delete these datas one by one.
dueio
  • 33
  • 5

1 Answers1

1

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()
    }
}
Shivam Gaur
  • 491
  • 5
  • 16
  • Yes but my keys is not simple. Almost keys are set as 'unique id'+'key.rawValue'. So I wonder this is the best way... – dueio Feb 07 '19 at 06:54
  • Hey dueio what is this unique id ,can you elobrate meanwhile I'm editing my answer to extent to what i understood your question – Shivam Gaur Feb 07 '19 at 07:15
  • ok then please look into the above answer you can change the unqKey variable here according to your username and while saving data use this enum also at the time of deletion. also make that uniquekey global constant, to change it as you need,Hope it helped!! – Shivam Gaur Feb 07 '19 at 07:45
  • If saved keys are not big, enum case will be better. But, in my case, for example, some key is combined like "username" + key.rawValue. (like user1+key1, user2+key1, user3+key1, user4+key1)... So I think that using 'suite' concept is better that using enum. – dueio Feb 07 '19 at 07:45
  • I just saw your new edited code! Yes I can use like that :) But, I confused which way is better between 'suite' and 'enum'. Code is more simple when use 'suite'.. – dueio Feb 07 '19 at 07:50
  • I think the enum way is more cleaner in code though,more readibiliy and no string literals wondering in code :p , I have not used suite till now, although looking in some examples you can implement it through suit also, and use enums at same time. :), hope I tried to give some insights!! – Shivam Gaur Feb 07 '19 at 07:57