0

i want to clear the complete storage in userDefault without using Remove Object method avaliable in userDefaults

this is func i wrote but not sure is this the write way of doing it.

  public func cleanCompleteStorage(){
        let domain = Bundle.module.bundleIdentifier
        UserDefaults.standard.removePersistentDomain(forName: domain)
        UserDefaults.standard.synchronize()
    }
Wahid Tariq
  • 159
  • 10
  • Try `UserDefaults.resetStandardUserDefaults()` and you don't need `synchronize` anymore – Shawn Frank Mar 24 '22 at 11:35
  • UserDefault Docs says This method has no effect and shouldn't be used. i tried that using playground but no effect – Wahid Tariq Mar 24 '22 at 11:37
  • If both of these haven't worked, then perhaps you can try user default's `dictionaryrepresentation` and `clear all` like so `UserDefaults.standard.dictionaryRepresentation().keys.forEach(defaults.removeObject(forKey:))` but it may also delete some data set by the app sandbox. However, it does use `removeObject forKey` – Shawn Frank Mar 24 '22 at 11:52
  • Could someone please address the fact that the documentation quite explicitly and unambiguously says "This method has no effect and shouldn't be used"? Are we all just going to gloss over that part? I understand that it might actually technically work, but surely we can't just ignore the documentation here? – damd Oct 25 '22 at 15:16

1 Answers1

0

Yes That code certainly removes all the userdefaults in storage. I manually verified by printing all the data before and after that code and it removes it. Personally using same code for my project.

Hashim Khan
  • 104
  • 3
  • It's better to only remove those keys you know and which are "yours". Deleting every key explicitly may cause undesired side effects. Some keys may not even be removable at all, since there origin is a read-only plist somewhere in the file system, or "managed app configurations". – CouchDeveloper Mar 24 '22 at 18:23