2016-10-05 7 views
0

SQLite 대신 Realm으로 데이터베이스를 변경 한 공유 프로젝트가 있습니다.Xamarin Realm - 닫을 때 영역

내 문제는 내 DatabaseManager의 영역을 닫으면 결과가 제거된다는 것입니다. 그러므로 나는 모든 DatabaseManager가 사용하는 영역의 정적 singelton 인스턴스를 만들었습니다. 이제 내 응용 프로그램이 메모리에 잠시 후 충돌하고 내 모든 데이터베이스 기능을 제거하면 작동합니다.

내 영역 인스턴스는 여기에 생성 :

public class RealmDatabase 
{ 
    private Realm mRealmDB; 
    public Realm RealmDB 
    { 
     get 
     { 
      if (mRealmDB == null || mRealmDB.IsClosed) 
      { 
       SetRealm(); 
      } 
      return mRealmDB; 
     } 
    } 

    static RealmDatabase cCurrentInstance; 
    public static RealmDatabase Current 
    { 
     get 
     { 
      if (cCurrentInstance == null) 
       cCurrentInstance = new RealmDatabase(); 

      return cCurrentInstance; 
     } 
    } 

    public RealmDatabase() 
    { 
    } 

    private void SetRealm() 
    { 
     var config = new RealmConfiguration ("DBName.realm", true); 
     mRealmDB = Realm.GetInstance (config); 
    } 

    public Transaction BeginTransaction() 
    { 
     return RealmDB.BeginWrite(); 
    } 
} 

의 I 내 DatabaseManagler는 다음과 같이보고했다 :

public class NewFreeUserManager 
{ 
    internal Realm RealmDB = RealmDatabase.Current.RealmDB; 
    static NewFreeUserManager cCurrentInstance; 
    public static NewFreeUserManager Current 
    { 
     get 
     { 
      if (cCurrentInstance == null) 
       cCurrentInstance = new NewFreeUserManager(); 

      return cCurrentInstance; 
     } 
    } 

    private NewFreeUserManager() 
    { 
    } 

    internal bool Save (FreeUser freeuser) 
    { 
     try 
     { 
      using (var trans = RealmDB.BeginWrite()) 
      { 
       RealmDB.RemoveAll<FreeUser>(); 
       var fu = RealmDB.CreateObject<FreeUser>(); 
       fu = freeuser; 
       trans.Commit(); 
      } 
      return true; 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine ("FreeUser save: " + e.ToString()); 
      return false; 
     } 
    } 

    internal FreeUser Get() 
    { 
     return RealmDB.All<FreeUser>().FirstOrDefault(); 
    } 
} 

이 사람이 나를 도울 수 있습니까?

답변

1

개체를 올바르게 유지하지 못하게하는 현재 설정에는 몇 가지 문제가 있습니다.

가장 중요한 첫 번째 이유는 영역 인스턴스가 스레드로부터 안전하지 않기 때문입니다. 즉, 다른 스레드에서 절대 액세스하지 않을 것이라는 확신이 들지 않으면 단독 스레드로 사용하는 것이 좋습니다.

두 번째는 더 미묘하지만에 저장 방법 당신은 요구하고있다 : 효과적으로, 당신이 영역에서 개체를 만드는 다음 다른 객체에 변수를 할당한다 무엇

var fu = RealmDB.CreateObject<FreeUser>(); 
fu = freeuser; 

. 이 경우 freeuser의 속성이 fu에 할당되지 않고 단지 하나의 참조를 다른 참조로 바꿉니다. 당신이 찾고있는 Realm.Manage 그래서 코드는 다음과 같이한다이다 : 두 번째 버그를 수정 한 후에는 더 이상 필요하지 않을 때

using (var trans = RealmDB.BeginWrite()) 
{ 
    RealmDB.Manage(freeuser); 
    trans.Commit(); 
} 

, 당신은 다시 닫 영역 인스턴스를 이동 할 수 있어야한다.

관련 문제