2011-10-12 1 views
2

내가 MonoTouch를 사용하여 아이폰 프로젝트에 일하고 있어요, 나는 직렬화 및 데이터 멤버로 CLLocation 유형과 교류 # 클래스에 속하는 단순 개체를 저장해야합니다MonoTouch : Serializable으로 표시되지 않은 유형 (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; 
} 

이 내 바이너리 직렬화 방법입니다 :

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

나는이 exceptio를 얻을 :이 코드를 실행할 때

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 위 클래스의 인스턴스) n :

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

CLLocation을 사용하여 클래스를 직렬화하는 방법이 있습니까?

답변

5

클래스가 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; 
     } 

    } 
} 
+0

감사합니다. 매력처럼 작동했습니다. –

2

당신은 MonoTouch 유형에 [Serializable]를 추가 할 수 없습니다. Dimitris 우수 제안에 대한 또 다른 대안은 자신의 유형에 ISerializable을 사용하는 것입니다.

이렇게하면 유형에서 데이터를 직렬화하는 방법을 완벽하게 제어 할 수 있습니다. 또한 두 가지 방법을 혼합하여 가능하면 [Serializable]을 사용하고 그렇지 않은 경우 ISerializable을 사용하십시오.

관련 문제