I have a List<Hashtable>
in my MonoTouch app, and I need to persist it to my settings. NSUserDefaults
, however, only takes in things that inherit from NSObject
.
Is there a simple way to wrap my List in an NSObject
that I can store in my settings, or is a quick generic way to encode and decode a Hashtable
to a JSON string (or similar)?
Or is there a MonoTouch alternative for persisting a small list of Hashtable
s?
Like @Maxim said there are several approach available. If you want to use NSUserDefaults
to store your data then you can serialize it (a .NET feature available to you using MonoTouch) to either:
a binary format. Then use the Stream
(or byte[]
) to create an NSData
instance that you'l be able to store with NSUserDefaults
; or
into a string and store it as a NSString
(string
overloads are also available, but it will do the NSString
conversion);
Why not save your data into SQLite-table?
You could create quiet simple table with fields:
- id - auto inc int - primary key;
- list name - string - to identify exact list;
- list data - byte[] - list's data.
For List -> byte[] (and vice versa) conversion try to use such code:
public static class Bytes
{
/// <summary>
/// Function to get byte array from a object
/// </summary>
/// <param name="_Object">object to get byte array</param>
/// <returns>Byte Array</returns>
public static byte[] ObjectToByteArray (object obj)
{
try {
var _MemoryStream = new MemoryStream ();
var _BinaryFormatter = new BinaryFormatter ();
_BinaryFormatter.Serialize (_MemoryStream, obj);
return _MemoryStream.ToArray ();
} catch (Exception _Exception) {
Console.WriteLine ("Exception caught in process: {0}", _Exception.ToString ());
}
return null;
}
public static T ByteArrayToObject<T> (byte[] arrBytes)
{
var memStream = new MemoryStream ();
var binForm = new BinaryFormatter ();
memStream.Write (arrBytes, 0, arrBytes.Length);
memStream.Seek (0, SeekOrigin.Begin);
var result = default(T);
try {
result = (T)binForm.Deserialize (memStream);
} catch (Exception ex) {
Console.WriteLine ("Deserialize error {0}", ex);
}
return result;
}
}