In Monotouch, is it possible to save a generic lis

2019-05-28 01:21发布

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 Hashtables?

2条回答
Root(大扎)
2楼-- · 2019-05-28 02:08

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);

查看更多
小情绪 Triste *
3楼-- · 2019-05-28 02:16

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;
    }
}
查看更多
登录 后发表回答