Forum Xamarin.iOS

Clear Specific NSUserDefaults.StandardUserDefaults

AndrewWoomerAndrewWoomer USMember ✭✭

If I'm setting keys using...

var prefs = NSUserDefaults.StandardUserDefaults;
prefs.SetString(key, "KEY");

Is there a way to clear all the keys under the prefs variable at the same time?

I know I can use prefs.Clear().Commit(); in Android. Is there anything similar in iOS? I don't want to clear all the defaults, only the ones defined under prefs.


Best Answer


  • LandLuLandLu Member, Xamarin Team Xamurai

    There're two ways to do this:
    1. Firstly get a list of all keys in the user defaults, then remove them all

    var prefs = NSUserDefaults.StandardUserDefaults;
    NSDictionary dic = prefs.ToDictionary();
    foreach (object key in dic.Keys)

    2. Use RemovePersistentDomain to achieve that:

    var prefs = NSUserDefaults.StandardUserDefaults;
    string appDomain = NSBundle.MainBundle.BundleIdentifier;
  • AndrewWoomerAndrewWoomer USMember ✭✭

    Thanks LandLu but for some reason that removed all my defaults. I have some set using...

    var login = NSUserDefaults.StandardUserDefaults;

    ...and both those methods cleared those also.

  • AndrewWoomerAndrewWoomer USMember ✭✭

    I thought something like that was going on. Thanks for all your help, @LandLu!

Sign In or Register to comment.