使用静态变量for realm数据库变量

时间:2016-12-15 02:35:39

标签: android xamarin xamarin.android realm static-variables

这是编写领域访问变量的更好方法吗?我正在使用静态变量,因为我注意到我只需要为其他类中的所有领域查询声明1个数据库连接。但我很好奇这是否仍然擅长编码标准。

using Realms;
using System;
using System.IO;

namespace RealmDatabase
{
    public class RealmDBAccessVariable
    {
        public static readonly string dbPath = 
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), 
            "default.realm");
        public static readonly RealmConfiguration config = new     RealmConfiguration(dbPath, true);
    }
}

2 个答案:

答案 0 :(得分:1)

这是我用于UI线程上的Realm实例的单例模式:

Xamarin.Android

public sealed class UIRealm
{
    static Realms.Realm instance;
    public UIRealm(Activity activity, RealmConfiguration config)
    {
        if (instance == null)
            activity.RunOnUiThread(() =>
            {
                instance = Realms.Realm.GetInstance(config);
            });
        else
            throw new Exception("A Realm instance has already be created");
    }

    public static Realms.Realm Instance
    {
        get
        {
            if (instance == null)
                throw new Exception("Call new UIRealm(Activity, RealmConfiguration) first");
            return instance;
        }
    }
}

用法:

// Create a UIRealm() only once
new UIRealm(this, new RealmConfiguration("realm.db"));
~~~
var aState = new State();
aState.Name = "WA";
UIRealm.Instance.Manage(aState);
var washingtonState = UIRealm.Instance.All<State>().Where((state => state.Name == "WA"));

Xamarin.Forms

public sealed class UIRealm
{
    static Realm instance;
    public UIRealm(RealmConfiguration config)
    {
        if (instance == null)
            Device.BeginInvokeOnMainThread(() =>
            {
                instance = Realm.GetInstance(config);
            });
        else
            throw new Exception("A Realm instance has already be created");
    }

    public static Realm Instance
    {
        get
        {
            if (instance == null)
                throw new Exception("Call new UIRealm(RealmConfiguration) first");
            return instance;
        }
    }
}

用法:

// Create a UIRealm() only once
new UIRealm(new RealmConfiguration("realm.db"));
~~~
var aState = new State();
aState.Name = "WA";
UIRealm.Instance.Manage(aState);
var washingtonState = UIRealm.Instance.All<State>().Where((state => state.Name == "WA"));

答案 1 :(得分:0)

我认为当您尝试在后台线程上写入Realm时,您很可能会遇到问题,并且您尝试访问在UI线程上打开的此操作的realm

static通常是不够的,ThreadLocal是用Java实现的。

我也不确定为什么这个对象是RealmObject。