KexAri
KexAri

Reputation: 3977

Removing a key from NSUserDefaults not working

I have a logout function in my app. Seems to be a weird problem where it doesn't save the NSUserDefaults. Here I simply want to remove the key. However after logging out if I then open the app again it will find that this key is still in the NSUserDefaults.

func didLogout() {
    // Clear user data
    let settings = NSUserDefaults.standardUserDefaults()
    settings.removeObjectForKey("userData")
    settings.synchronize()

    unregisterForRemoteNotifications()

    openLoginScreen()
}

Any ideas what I could be doing wrong here?

Upvotes: 8

Views: 6021

Answers (6)

Adam Smaka
Adam Smaka

Reputation: 6393

try this

    DispatchQueue.main.async {
        UserDefaults.standard.removeObject(forKey: YOUR_KEY_HERE)
    }

helped for me

Upvotes: 3

David Gish
David Gish

Reputation: 750

One of our (XCTest) unit tests was failing every other run. It turned out that -removeObjectForKey: was — inexplicably — only working every other run. I verified this with defaults.dictionaryRepresentation before and after -removeObjectForKey:. I thought perhaps the keys were being added to two domains and the first remove wasn't getting them both (the docs say this can happen) so I cleverly added a second remove, but that also had no effect. My solution was to set the key to the uninitialized value instead.

Any ideas?

Upvotes: 2

Mr. Bean
Mr. Bean

Reputation: 4281

I did the following to delete the userdefault of the app on user loggout

private static let userDefaults = NSUserDefaults.standardUserDefaults()
  private static let userTokenKey = "userTokenKey"
 userDefaults.removeObjectForKey(userTokenKey)
    userDefaults.synchronize()

Upvotes: 1

Nayana
Nayana

Reputation: 128

The code above is correct. The key will be still there, but it will return only nil value. So, when user logout you can set

NSUserDefaults.standardUserDefaults().removeObjectForKey("userData")

and when new user login you can set new value by checking

if NSUserDefaults.standardUserDefaults().objectForKey("userData") == nil

Upvotes: 2

FranMowinckel
FranMowinckel

Reputation: 4343

removeObjectForKey(_:)

Removing a default has no effect on the value returned by the objectForKey: method if the same key exists in a domain that precedes the standard application domain in the search list.

Just use another key instead of userData. It might exists in another domain.

Upvotes: 3

ak2g
ak2g

Reputation: 1673

There is no issue in your above code you might have set data in app delegate or when you login your app, or you have mistyped key value.

If you want to clear all data. This will Work

let appDomain = NSBundle.mainBundle().bundleIdentifier!
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)

Upvotes: 1

Related Questions