I have been playing with this for a few hours and I’m stuck. I’m trying to save a list of Favorite objects in the NSUserDefaults using Monotouch. I believe that I am on the right track but I just can’t quite get it… here are my model objects:
public class Favorite {
public Favorite (){}
public string Description {get;set;}
public Song Song {get;set;}
}
public class Song {
public Song (){}
public string Name {get;set;}
public string Artist {get;set;}
}
Next, I want to save a list of Favorites that the user has selected. From what I have read, I can use an NSArray to save a list of items in the NSUserDefaults. So how do I go from a List of Favorites to an NSArray of Favorites… I haven’t been able to find any documentation on this. Here is my Settings wrapper:
public class Settings {
private static string _favoritesKey = "favorites";
public static IList<Favorite> Favorites {get;set;}
public static void Add(Favorite favorite){
Favorites.Add(favorite);
}
public static void Remove(Favorite favorite){
Favorites.Remove(favorite);
}
public static void Read()
{
var tempFavorites = (NSArray)NSUserDefaults.StandardUserDefaults[_favoritesKey];
if(tempFavorites == null){
Favorites = new List<Favorite>();
}
else {
for(uint i=0;i<tempFavorites.Count;i++){
var fav = tempFavorites.ValueAt(i); //returns IntPtr
// do something to convert to Favorite
// Favorites.Add(converted_favorite);
}
}
}
public static void Write()
{
var tempArray = Favorites.ToArray();
// convert to NSObject[]
NSUserDefaults.StandardUserDefaults[_favoritesKey] = NSArray.FromNSObjects(converted_array);
NSUserDefaults.StandardUserDefaults.Synchronize();
}
}
Am I on the right track? It looks like all I need to do is figure out how to convert to and from NSObjects. Also, if I am saving these custom objects in NSUserDefaults, do they need to be serializable? Much thanks!
If you want to do this, you would need your Favorite class to be a NSObject with native storage that you synchronize with the [Connect] attribute, something like this:
You would do the same for your Song class. You can only store native classes in the NSStandardUserDefaults object store.
An alternative would be what Jason suggested and just serialize to a string and then store that as a NSString.