Atlas Device SDK 已弃用。 有关详细信息,请参阅弃用页面。
Overview
Realm提供 RealmInteger作为特殊整数类型,您可以将其用作逻辑计数器。 RealmInteger<T> 公开了一个额外的API ,可以在使用 Synchronized Realm 时更清楚地Express意图并生成更好的冲突解决步骤。 类型参数<T>的类型可以是byte 、 short 、 int或long 。 以下示例展示了如何使用映射到int的RealmInteger属性:
public partial class MyRealmClass : IRealmObject { [] public int _id { get; set; } public RealmInteger<int> Counter { get; set; } }
实施计数器
传统上,您会通过以下方式实现计数器:读取值,递增该值,然后设置该值 ( myObject.Counter += 1 )。 这在异步情况下(例如两个客户端离线时)效果不佳。 考虑以下场景:
Realm 对象具有类型为
int的counter属性。 目前其值设置为10。客户端 1 和 2 均会读取
counter属性 (10),并分别将该值递增1。当每个客户端重新获得连接并合并其更改时,它们期望的值为 11,并且不存在冲突。 但是,计数器值应为
12!
但是,在使用RealmInteger时,您可以调用Increment()和Decrement()方法,要重置计数器,请将其设置为0 ,就像重置int一样:
var myObject = realm.Find<MyRealmClass>(id); // myObject.Counter == 0 realm.Write(() => { // Increment the value of the RealmInteger myObject.Counter.Increment(); // 1 myObject.Counter.Increment(5); // 6 // Decrement the value of the RealmInteger // Note the use of Increment with a negative number myObject.Counter.Decrement(); // 5 myObject.Counter.Increment(-3); // 2 // Reset the RealmInteger myObject.Counter = 0; // RealmInteger<T> is implicitly convertable to T: int bar = myObject.Counter; });
重要
重置RealmInteger时,可能会遇到上述离线合并问题。
RealmInteger由传统的integer类型支持,因此将属性类型从T更改为RealmInteger<T>时,无需迁移模式。