Peter Frying
Peter Frying

Reputation: 1

After deleting persistent data in NSUserDeafults, how do I reset my application

I have a bunch of NSUserDefault settings and on the settings page I have a "Reset settings" button that calls this method:

@IBAction func resetData(sender: AnyObject) {
    let appDomain : NSString = NSBundle.mainBundle().bundleIdentifier!
    NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)
    println("Settings reset")
}

How do I then reset the application to "erase" all the saved data and display a fresh application?

Thank you in advanced

Upvotes: 0

Views: 69

Answers (1)

Zell B.
Zell B.

Reputation: 10296

Notice that user defaults has e method called dictionaryRepresentation that returns all user defaults represented as dictionary. To erase all the data loop through that dictionary and remove object for each key

var userDefaults =  NSUserDefaults.standardUserDefaults().dictionaryRepresentation()

for (key,value) in userDefaults{

    NSUserDefaults.standardUserDefaults().removeObjectForKey(key as String)

}

If you need to refresh your UI after erasing data consider creating a method where you set your view state based on user defaults even if any key value is nil then call this method when the view is loaded or reset button is pressed

Upvotes: 1

Related Questions