Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults.StandardUserDefaults - saving and retrieving a Dictionary

Would you guys help me? I found how to save and retrieve simple objects to use them as app settings.

NSUserDefaults.StandardUserDefaults.SetString("testUser","username");
NSUserDefaults.StandardUserDefaults.Init(); //Although it's strange that you have to call this method to actually save your stuff

and later you can retrieve it like that:

var username = NSUserDefaults.StandardUserDefaults.StringForKey("username");

Now, what if I need to save multiple usernames (as many as I want)? And what if I need to save multiple usernames with passwords or passhashes?

like image 689
iLemming Avatar asked Oct 05 '11 15:10

iLemming


1 Answers

Here's an example for arrays (many strings kept with a single key):

        NSUserDefaults.StandardUserDefaults ["array"] = NSArray.FromStrings ("a", "b", "c");
        foreach (string s in NSUserDefaults.StandardUserDefaults.StringArrayForKey ("array")) {
            Console.WriteLine (s);
        }

And an example where a dictionary (key=value) is kept with a single key:

        NSDictionary dict = NSDictionary.FromObjectsAndKeys (new object[] { "user1", "user2" }, new object[] { "123", "abc" });
        NSString key = new NSString ("dict");
        NSUserDefaults.StandardUserDefaults.SetValueForKey (dict, key);
        NSDictionary d2 = NSUserDefaults.StandardUserDefaults.DictionaryForKey (key);
        for (int i = 0; i < d2.Count; i++) {
            Console.WriteLine ("{0} : {1}", d2.Keys [i], d2.Values [i]);
        }
like image 109
poupou Avatar answered Oct 06 '22 01:10

poupou