ios - 单点触控 : How to serialize a type (like CLLocation) not marked as Serializable?

标签 ios serialization xamarin.ios serializable cllocation

我正在使用 MonoTouch 处理一个 iPhone 项目,我需要序列化并保存一个属于 C# 类的简单对象,并将 CLLocation 类型作为数据成员:

[Serializable]
public class MyClass
{
    public MyClass (CLLocation gps_location, string location_name)
    {
        this.gps_location = gps_location;
        this.location_name = location_name;
    }

    public string location_name;
    public CLLocation gps_location;
}

这是我的二进制序列化方法:

static void SaveAsBinaryFormat (object objGraph, string fileName)
    {
        BinaryFormatter binFormat = new BinaryFormatter ();
        using (Stream fStream = new FileStream (fileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
            binFormat.Serialize (fStream, objGraph);
            fStream.Close ();
        }
    }

但是当我执行这段代码时(myObject 是上述类的一个实例):

try {
            SaveAsBinaryFormat (myObject, filePath);
            Console.WriteLine ("object Saved");
        } catch (Exception ex) {
            Console.WriteLine ("ERROR: " + ex.Message);
        }

我得到这个异常:

ERROR: Type MonoTouch.CoreLocation.CLLocation is not marked as Serializable.

有没有办法用 CLLocation 序列化一个类?

最佳答案

由于一个类没有被SerializableAttribute标记,所以它不能被序列化。但是,通过一些额外的工作,您可以从中存储您需要的信息并对其进行序列化,同时将其保存在您的对象中。

您可以通过为它创建一个属性来完成此操作,并根据您希望从中获取的信息使用适当的后备存储。例如,如果我只想要 CLLocation 对象的坐标,我将创建以下内容:

[Serializable()]
public class MyObject
{

    private double longitude;
    private double latitude;
    [NonSerialized()] // this is needed for this field, so you won't get the exception
    private CLLocation pLocation; // this is for not having to create a new instance every time

    // properties are ok    
    public CLLocation Location
    {
        get
        {
            if (this.pLocation == null)
            {
                this.pLocation = new CLLocation(this.latitude, this.longitude);
            }
            return this.pLocation;

        } set
        {
            this.pLocation = null;
            this.longitude = value.Coordinate.Longitude;
            this.latitude = value.Coordinate.Latitude;
        }

    }
}

关于ios - 单点触控 : How to serialize a type (like CLLocation) not marked as Serializable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7744054/

相关文章:

c# - 如何将数据传递给 MonoTouch.Dialog 的委托(delegate)?

Xamarin.iOS - 64 位升级

ios - fatal error : unexpectedly found nil while unwrapping an Optional value on sendSynchronousRequest

c# - 反序列化异常: Unable to find assembly

JQuery 序列化所有表单字段

java - 序列化包含对象java的对象

ios - 谁保留 block ?

ios - 以编程方式设置图像高度时不起作用

ios - 类型 '(String, AnyObject)' 在 swift 中没有下标成员

c# - 如何使用 Xamarin Form 将流形式的图像上传到多部分休息服务