Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all UserDefaults data ? - Swift [duplicate]

I have this code to remove all UserDefaults data from the app:

let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)

print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)

But I got 10 from the print line. Shouldn't it be 0?

like image 559
Zizoo Avatar asked Oct 16 '22 22:10

Zizoo


People also ask

How do I delete Data from UserDefaults?

To remove a key-value pair from the user's defaults database, you need to invoke removeObject(forKey:) on the UserDefaults instance. Let's update the previous example. The output in the console confirms that the removeObject(forKey:) method works as advertised.

Is UserDefaults synchronous?

Yes it is synchronous .

How get Data from UserDefaults in swift 5?

In order to get data from UserDefaults, use one of its type dedicated get methods, or a generic object(forKey:) method. Note that the return value of the above array method is an optional. Nil will be returned if the given key does not exist or if its value is not an array.

Where are UserDefaults stored?

Storing Data in User Defaults The user's defaults database is stored on disk as a property list or plist. A property list or plist is an XML file. At runtime, the UserDefaults class keeps the contents of the property list in memory to improve performance.


2 Answers

The problem is you are printing the UserDefaults contents, right after clearing them, but you are not manually synchronizing them.

let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)

This should do the trick.

Now you don't normally need to call synchronize manually, as the system does periodically synch the userDefaults automatically, but if you need to push the changes immediately, then you need to force update via the synchronize call.

The documentation states this

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

like image 126
Lefteris Avatar answered Oct 19 '22 12:10

Lefteris


This answer found here https://stackoverflow.com/a/6797133/563381 but just incase here it is in Swift.

func resetDefaults() {
    let defaults = UserDefaults.standard
    let dictionary = defaults.dictionaryRepresentation()
    dictionary.keys.forEach { key in
        defaults.removeObject(forKey: key)
    }
}
like image 75
Ryan Poolos Avatar answered Oct 19 '22 12:10

Ryan Poolos