Reputation: 36214
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?
Upvotes: 11
Views: 7086
Reputation: 4600
I had trouble getting NSUserDefaults
to store dictionaries. What I ended up doing, is simply obtaining the Documents directory, and saving my dictionary to a file when the app is terminating or going to the background, then loading it from a file when the app finishes loading. NSDictionary
and NSMutableDictionary
have class methods that load or save from a file - and it uses serialized XMLs, so it's nice and elegant.
This is good if your app doesn't need a large amount of data, and the data is simple and structure is fluid.
Upvotes: 1
Reputation: 43553
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]);
}
Upvotes: 12
Reputation: 2458
I would consider using core-data if you have a lot of users you also want to search for and filter. If your app is not that complex, you can always serialize a dictionary into a string and save it as such in the user defaults. A good library for JSON (de)serialization is SBJSON http://stig.github.com/json-framework/.
Upvotes: 1