56

How to delete data from NSUserDefaults? There is quite a few answers how to do it in Objective C, but how about Swift? So I tried this:

let defaults = NSUserDefaults.standardUserDefaults()
    defaults.removeObjectForKey("myKey")

Didn't work. Maybe what I really want to delete is not NSUserDefaults? This is how I save data:

class MySavedData: NSObject, NSCoding {
    var image: String

    init(name: String, image: String) {
        self.image = image
    }

    required init(coder aDecoder: NSCoder) {
        image = aDecoder.decodeObjectForKey("image") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(image, forKey: "image")
    }
}

class ViewController: <...> {
    var myData = [MySavedData]() //Later myData gets modified and then function save() is called

    func save() {
        let savedData = NSKeyedArchiver.archivedDataWithRootObject(myData)
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(savedData, forKey: "myKey")
    }
}

EDIT: Just to clear some things - data that is being saved is small (not even close to 100kb)

And maybe I am saving data not to NSUserDefaults (I am new to programming), so here is how I get it (load):

let defaults = NSUserDefaults.standardUserDefaults()
if let savedData = defaults.objectForKey("myData") as? NSData {
    myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedData) as! [UserLogin]
    }
Xernox
  • 1,706
  • 1
  • 23
  • 37
  • 4
    `removeObjectForKey` is the correct method. What do you mean by "it didn't work"? – Paulw11 Dec 17 '15 at 09:39
  • 1
    Missing `synchronize`? – Larme Dec 17 '15 at 09:40
  • You need to synchronize to commit changes into NSUserDefaults. – Dipen Panchasara Dec 17 '15 at 09:42
  • 4
    Synchronize is [not generally useful](https://developer.apple.com/library/ios/releasenotes/Foundation/RN-Foundation/): *"You should only need to call -synchronize if a separate application will be reading the default that you just set, or if a process that does not use AppKit is terminating."* – jtbandes Dec 17 '15 at 09:44
  • @Paulw11 By "it didn't work" my app is still gets stored value. Well at least `print(myData[0].image)` still prints value that was set before. – Xernox Dec 17 '15 at 11:02
  • Is this after you have terminated the app and restarted it? removing the value from defaults won't affect any existing in-memory instances – Paulw11 Dec 17 '15 at 11:14
  • So, actually `removeObjectForKey` deletes value for key as expected. I made mistake by assigning "myKeys" key value to a variable and I was checking that variables value, not keys. – Xernox Dec 17 '15 at 12:05

11 Answers11

96

removeObjectForKey is the right way to go.
This will remove the value for the selected key. The following code sets a string value for a key in NSUserDefaults, prints it and then uses removeObjectForKey to remove and print the key value again. After removeObjectForKey the value is nil.

let prefs = NSUserDefaults.standardUserDefaults()
var keyValue = prefs.stringForKey("TESTKEY")
print("Key Value not set \(keyValue)")
let strHello = "HELLO WORLD"

prefs.setObject(strHello, forKey: "TESTKEY")
keyValue = prefs.stringForKey("TESTKEY")
print("Key Value \(keyValue)")

prefs.removeObjectForKey("TESTKEY")
keyValue = prefs.stringForKey("TESTKEY")
print("Key Value after remove \(keyValue)")

Returns:

Key Value not set nil

Key Value Optional("HELLO WORLD")

Key Value after remove nil

Update Swift 3:

let prefs = UserDefaults.standard
keyValue = prefs.string(forKey:"TESTKEY")
prefs.removeObject(forKey:"TESTKEY")
ymutlu
  • 6,585
  • 4
  • 35
  • 47
Peter Todd
  • 8,561
  • 3
  • 32
  • 38
18

The code you have written will work fine, but NSUserDefaults synchronise at certain time interval.

As you want that should reflect in NSUserDefaults immediately ,so u need to write synchronise

let defaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("myKey") 
defaults.synchronize()
sourav
  • 779
  • 5
  • 14
  • 1
    What is the issue still now ? check what is in defaults by keeping break point . – sourav Dec 17 '15 at 11:07
  • Oh, I think I got the mistake, I clear NSUserdafaults, but variable in ViewController (myData) still contains the value! – Xernox Dec 17 '15 at 11:13
13

Try This

NSUserDefaults.standardUserDefaults().removePersistentDomainForName(NSBundle.mainBundle().bundleIdentifier!)

for Swift 3

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

But this will clear all values from NSUserDefaults.careful while using.

ErasmoOliveira
  • 1,416
  • 2
  • 20
  • 40
Avijit Nagare
  • 8,482
  • 7
  • 39
  • 68
8

Removing UserDefaults for key in swift 3, based upon the top answer, just slightly different syntax:

UserDefaults.standard.removeObject(forKey: "doesContractExist")
Daniel Jones
  • 1,032
  • 10
  • 18
6

Swift 4.x Remove all key in UserDefaults

let defaults = UserDefaults.standard
let dictionary = defaults.dictionaryRepresentation()

    dictionary.keys.forEach 
    { key in   defaults.removeObject(forKey: key)
    }
Kandhal Bhutiya
  • 198
  • 1
  • 9
3

I would go for a solution which setting the value to nil for a key.

Swift 3

UserDefaults.standard.set(nil, forKey: "key")

Swift 2.x

NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "key")

NOTE: that is a clear and straight statement, but bear in mind there is a limit to store information in NSUserDefaults, it is definitely not the right place to store large binary files (like e.g. images) – for that there is a Documents folder. however it is not defined how big the var image: String which you encode/decode.

holex
  • 23,961
  • 7
  • 62
  • 76
3

Use following for loop:

for key in NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys {
   NSUserDefaults.standardUserDefaults().removeObjectForKey(key.description)
}
D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
Gaurav Gudaliya
  • 131
  • 1
  • 1
  • 9
1

To nuke all UserDefaults keys, you can use the following code in Swift 3.x:

UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
Adrian
  • 16,233
  • 18
  • 112
  • 180
1

In Swift 5.0, iOS 15 below single line of code is enough.

UserDefaults.standard.dictionaryRepresentation().keys.forEach(defaults.removeObject(forKey:))

Or try this

if let appDomain = Bundle.main.bundleIdentifier {
   UserDefaults.standard.removePersistentDomain(forName: appDomain)
}
Naresh
  • 16,698
  • 6
  • 112
  • 113
0
func  remove_pref(remove_key : String){
    UserDefaults.standard.removeObject(forKey: remove_key)
    UserDefaults.standard.synchronize()
}
Softlabsindia
  • 791
  • 6
  • 11
  • According to Apples documentation " .synchronize() this method is unnecessary and shouldn't be used." – OverD Dec 22 '22 at 14:47
-1

Update code for Swift : Used below line of code to Delete key values for NSUserDefaults in Swift

UserDefaults.standard.setValue(nil, forKey: "YouEnterKey")
Kiran Jadhav
  • 3,209
  • 26
  • 29