Los SDK de dispositivos Atlas están obsoletos. Consulte deprecation page for details.
Acerca de los ejemplos en esta página
Los ejemplos de esta página utilizan el modelo de datos de una aplicación de gestión de proyectos que tiene dos tipos de objetos Realm: Project
y Task. Un Project tiene cero o más Tasks.
See the schema for these two classes, Project and Task, below:
ProjectTask.java
import org.bson.types.ObjectId;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;
publicclassProjectTaskextendsRealmObject {
@PrimaryKey
public ObjectId _id;
@Required
public String name;
public String assignee;
publicint progressMinutes;
publicboolean isComplete;
publicint priority;
@Required
public String _partition;
}
Project.java
import org.bson.types.ObjectId;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;
publicclassProjectextendsRealmObject {
@PrimaryKey
public ObjectId _id;
@Required
public String name;
public RealmList<ProjectTask> tasks = newRealmList<>();
}
ProjectTask.kt
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
import org.bson.types.ObjectId
openclassProjectTask(
@PrimaryKey
var _id: ObjectId = ObjectId(),
@Required
var name: String = "",
var assignee: String? = null,
var progressMinutes: Int = 0,
var isComplete: Boolean = false,
var priority: Int = 0,
var _partition: String = ""
): RealmObject()
Project.kt
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
import org.bson.types.ObjectId
openclassProject(
@PrimaryKey
var _id: ObjectId = ObjectId(),
@Required
var name: String = "",
var tasks: RealmList<ProjectTask> = RealmList(),
): RealmObject()
Modify an Object
Within a transaction, you can update a Realm object the same way you would update any other object in your language of choice. Just assign a new value to the property or update the property.
El siguiente ejemplo cambia el nombre de la tortuga a "Archibald" y establece la edad de Archibald en 101 asignando nuevos valores a las propiedades:
realm.executeTransaction(r -> {
// Get a turtle to update.
Turtleturtle= r.where(Turtle.class).findFirst();
// Update properties on the instance.
// This change is saved to the realm.
turtle.setName("Archibald");
turtle.setAge(101);
});
realm.executeTransaction { r: Realm ->
// Get a turtle to update.
val turtle = r.where(Turtle::class.java).findFirst()
// Update properties on the instance.
// This change is saved to the realm.
turtle!!.name = "Archibald"
turtle.age = 101
}
Upsert an Object
An upsert is a write operation that either inserts a new object with a given primary key or updates an existing object that already has that primary key. We call this an upsert because it is an "update or insert" operation. This is useful when an object may or may not already exist, such as when bulk importing a dataset into an existing realm. Upserting is an elegant way to update existing entries while adding any new entries.
El siguiente ejemplo muestra cómo insertar un objeto con realm. Creamos un nuevo entusiasta de las tortugas llamado "Drew" y luego actualizamos su nombre a "Andy" usando insertarOActualizar():
realm.executeTransaction(r -> {
ObjectIdid=newObjectId();
TurtleEnthusiastdrew=newTurtleEnthusiast();
drew.set_id(id);
drew.setName("Drew");
drew.setAge(25);
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew);
TurtleEnthusiastandy=newTurtleEnthusiast();
andy.set_id(id);
andy.setName("Andy");
andy.setAge(56);
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
r.insertOrUpdate(andy);
});
realm.executeTransaction { r: Realm ->
val id = ObjectId()
val drew = TurtleEnthusiast()
drew._id = id
drew.name = "Drew"
drew.age = 25
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew)
val andy = TurtleEnthusiast()
andy._id = id
andy.name = "Andy"
andy.age = 56
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
r.insertOrUpdate(andy)
}
También puede usar copyToRealmOrUpdate() para crear un nuevo objeto basado en un objeto proporcionado o actualizar un objeto existente con el mismo valor de clave principal. Use el indicador de CHECK_SAME_VALUES_BEFORE_SETimportación para actualizar únicamente los campos que sean diferentes en el objeto proporcionado:
The following example demonstrates how to insert an object or, if an object already exists with the same primary key, update only those fields that differ:
realm.executeTransaction(r -> {
ObjectIdid=newObjectId();
TurtleEnthusiastdrew=newTurtleEnthusiast();
drew.set_id(id);
drew.setName("Drew");
drew.setAge(25);
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew);
TurtleEnthusiastandy=newTurtleEnthusiast();
andy.set_id(id);
andy.setName("Andy");
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
// the flag passed ensures that we only write the updated name field to the db
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew)
val andy = TurtleEnthusiast()
andy._id = id
andy.name = "Andy"
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
r.copyToRealmOrUpdate(andy,
ImportFlag.CHECK_SAME_VALUES_BEFORE_SET)
}
Update a Collection
Realm supports collection-wide updates. A collection update applies the same update to specific properties of several objects in a collection at once.
El siguiente ejemplo demuestra cómo actualizar una colección. Gracias a la relación inversa implícita entre la propiedad owner de Turtle y la propiedad turtles de TurtleEnthusiast, Realm actualiza automáticamente la lista de tortugas de Josephine cuando se usa setObject() para actualizar la propiedad "propietario" de todas las tortugas de la colección.
Como las colecciones realm siempre reflejan el último estado, pueden aparecer, desaparecer o cambiar mientras se recorre una colección. Para obtener una colección estable sobre la que se pueda iterar, se puede crear una snapshot de los datos de una colección. Un snapshot garantiza que el orden de los elementos no cambie, incluso si se elimina o modifica algún elemento.
Iterator Los objetos creados a partir de RealmResults usan instantáneas automáticamente. Iterator Los objetos creados a partir de RealmList instancias no usan instantáneas. Use RealmList.createSnapshot() o RealmResults.createSnapshot() para generar manualmente una instantánea que pueda iterar manualmente:
El siguiente ejemplo demuestra cómo iterar de forma segura sobre una colección utilizando un snapshot implícito creado a partir de un RealmResultsIterator o un snapshot manual creado a partir de un RealmList: