Atlas Device SDK 已弃用。 有关详细信息,请参阅弃用页面。
10.5.0 版本中的新增功能。
Overview
您可以使用dictionary 数据类型来管理一系列唯一字符串键值对组成的集合。dictionary 数据映射到 Javascript 对象 类型。
Realm 对象模型
要在模式中定义混合值的字典,请将字段的数据类型设置为空对象 "{}" 。或者,要创建包含特定类型值的字典,请在括号前添加数据类型。例如,使用 "int{}" 指定字典值必须是整数,或使用 "string{}" 指定字典值必须是字符串。
const PersonSchema = { name: "Person", properties: { name: "string", home: "{}", }, };
Realm 不允许在映射键中使用 . 或 $ 字符。您可以使用百分比编码和解码来存储包含这些不允许的任一字符的映射键。
// Percent encode . or $ characters to use them in map keys const mapKey = "kitchen.windows"; const encodedMapKey = mapKey.replace(".", "%2E");
创建附带字典值的对象
通过运行 realm.create() 创建带有字典值的对象写事务中的方法。
let johnDoe; let janeSmith; realm.write(() => { johnDoe = realm.create("Person", { name: "John Doe", home: { windows: 5, doors: 3, color: "red", address: "Summerhill St.", price: 400123, }, }); janeSmith = realm.create("Person", { name: "Jane Smith", home: { address: "100 northroad st.", yearBuilt: 1990, }, }); });
查询附带字典属性的对象
要过滤查询,运行集合() 以根据一个或多个对象属性的值指定结果子集。您可以使用方括号表示法。根据字典属性的值指定结果。
您还可以使用 <dictionary>.@keys 或 <dictionary>.@values 来确定结果集合是否包含某个键或值。例如,如果您有一个附带嵌套 home 字典的 Person 集合,则可通过运行查询 home.@keys = "price" 来返回附带具有 "price" 属性的 home 的所有 Person 对象。
// query for all Person objects const persons = realm.objects("Person"); // run the `.filtered()` method on all the returned persons to // find the house with the address "Summerhill St." const summerHillHouse = persons.filtered( `home['address'] = "Summerhill St."` )[0].home; // Find all people that have a house with a listed price const peopleWithHousesWithAListedPrice = persons.filtered( `home.@keys = "price" ` ); // find a house that has any field with a value of 'red' const redHouse = persons.filtered(`home.@values = "red" `)[0].home;
将侦听器添加到字典中
您可以通过运行dictionary.addListener()向字典添加侦听器 方法。 addListener方法的回调函数有两个参数,一个是已更改的字典,另一个是描述字典更改方式的更改数组。
注意
了解有关变更通知的更多信息。
summerHillHouse.addListener((changedHouse, changes) => { console.log("A change has occurred to the Summer Hill House object"); });
更新字典
要更新字典的属性,请使用点符号或 dictionary.put() 方法。
realm.write(() => { // use the `set()` method to update a field of a dictionary summerHillHouse.set({ price: 400100 }); // alternatively, update a field of a dictionary through dot notation summerHillHouse.color = "brown"; // update a dictionary by adding a field summerHillHouse.yearBuilt = 2004; });
删除字典成员
要删除字典的成员,请使用 dictionary.remove() 方法,其中包含要从字典删除的属性数组。
realm.write(() => { // remove the 'windows' and 'doors' field of the Summerhill House. summerHillHouse.remove(["windows", "doors"]); });