Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
Kit de desarrollo de software de Swift

Model Data - Swift SDK

Realm applications model data as objects composed of field-value pairs that each contain one or more supported data types.

Los objetos Realm son clases Swift u Objective-C estándar, pero también incorporan características adicionales como consultas en tiempo real. El SDK de Swift asigna objetos Realm directamente a objetos nativos de Swift u Objective-C, lo que significa que no es necesario usar una biblioteca especial de acceso a datos, como... ORM. En cambio, puedes trabajar con objetos Realm como lo harías con cualquier otra instancia de clase.

Cada objeto de Realm se ajusta a un tipo de objeto específico, que es esencialmente una clase que define las propiedades y relaciones de los objetos de ese tipo. Realm garantiza que todos los objetos de un reino se ajusten al esquema de su tipo y valida los objetos cada vez que se crean, modifican o eliminan.

Ejemplo

El siguiente esquema define un Dog tipo de objeto con un nombre de cadena, raza de cadena opcional, fecha de nacimiento e ID de clave principal.

// A dog has an _id primary key, a string name, an optional
// string breed, and a date of birth.
@interface Dog : RLMObject
@property RLMObjectId *_id;
@property NSString *name;
@property NSString *breed;
@property NSDate *dateOfBirth;
@end
@implementation Dog
+ (NSString *)primaryKey {
return @"_id";
}
+ (NSArray<NSString *> *)requiredProperties {
return @[
@"_id", @"name", @"dateOfBirth"
];
}
@end
// A dog has an _id primary key, a string name, an optional
// string breed, and a date of birth.
class Dog: Object {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name = ""
@Persisted var breed: String?
@Persisted var dateOfBirth = Date()
}

A realm schema is a list of valid object schemas that a realm may contain. Every Realm object must conform to an object type that's included in its realm's schema.

By default, the Swift SDK automatically adds all classes in your project that derive from RLMObject or RLMEmbeddedObject to the realm schema.

Tip

Configure Your Realm Schema

To control which classes Realm adds to a realm schema, see Provide a Subset of Classes to a Realm.

Si un realm ya contiene datos cuando lo abres, Realm valida cada objeto para garantizar que se haya proporcionado un esquema de objeto para su tipo y que cumpla con todas las restricciones especificadas en el esquema.

Tip

Learn How to Work With a Realm

For code examples that show how to configure and open a realm in the Swift SDK, see Configure & Open a Realm - Swift SDK.

You can subclass Realm models to share behavior between classes, but there are limitations. In particular, Realm does not allow you to:

  • Conversión entre clases polimórficas: subclase a subclase, subclase a padre, padre a subclase

  • Query en varias clases simultáneamente: por ejemplo, "obtener todas las instancias de la clase principal y la subclase"

  • Contenedores de múltiples clases: List y Results con una mezcla de clase padre y subclase.

Tip

Check out the code samples for working around these limitations.

New in version 10.10.0: While you can't mix @Persisted and @objc dynamic property declarations within a class, you can mix the notation styles across base and subclasses. For example, a base class could have a @Persisted var foo: Int property, and a subclass could have an @objc dynamic var bar = 0 property, with both persisted. However, the @objc dynamic property would be ignored if the @Persisted property were within the same base or subclass.

Realm does not support Swift structs as models for a variety of reasons. Realm's design focuses on "live" objects. This concept is not compatible with value type structs. By design, Realm provides features that are incompatible with these semantics, such as:

That said, it is sometimes useful to detach objects from their backing realm. This typically isn't an ideal design decision. Instead, developers use this as a workaround for temporary limitations in our library.

You can use key-value coding to initialize an unmanaged object as a copy of a managed object. Then, you can work with that unmanaged object like any other NSObject.

let standaloneModelObject = MyModel(value: persistedModelObject)

Tu modelo de objeto Realm es una colección de propiedades. En el nivel más básico, cuando creas tu modelo, tus declaraciones le dan a Realm información sobre cada propiedad:

  • The data type and whether the property is optional or required

  • Si Realm debe almacenar o ignorar la propiedad

  • Si la propiedad es una llave primaria o se debe indexar

Las propiedades también son el mecanismo para establecer relaciones entre los tipos de objetos de Realm.

The Realm Swift SDK uses reflection to determine the properties in your models at runtime. Your project must not set SWIFT_REFLECTION_METADATA_LEVEL = none, or Realm cannot discover children of types, such as properties and enum cases. Reflection is enabled by default if your project does not specifically set a level for this setting.

New in version 10.21.0.

Puedes trabajar con un subconjunto de las propiedades del objeto Realm creando una proyección de clase. Una proyección de clase es una clase que pasa o transforma algunas o todas las propiedades del objeto Realm. La proyección de clase te permite crear modelos de vista que utilizan una abstracción del Modelo de objeto. Esto simplifica el uso y prueba de objetos Realm en tu aplicación.

With class projection, you can use a subset of your object's properties directly in the UI or transform them. When you use a class projection for this, you get all the benefits of Realm's live objects:

  • The class-projected object live updates

  • You can observe it for changes

  • You can apply changes directly to the properties in write transactions

Realm doesn't use bridge tables or explicit joins to define relationships as you would in a relational database. Realm handles relationships through embedded objects or reference properties to other Realm objects. You read from and write to these properties directly. This makes querying relationships as performant as querying against any other property.

Realm supports to-one, to-many, and inverse relationships.

A to-one relationship means that an object relates to one other object. You define a to-one relationship for an object type in its object schema. Specify a property where the type is the related Realm object type. For example, a dog might have a to-one relationship with a favorite toy.

Tip

To learn how to define a to-one relationship, see Define a To-One Relationship Property.

Una relación de uno a muchos significa que un objeto se relaciona con más de otro objeto. En Realm, una relación de uno a muchos es una lista de referencias a otros objetos. Por ejemplo, una persona podría tener muchos perros.

A List represents the to-many relationship between two Realm types. Lists are mutable: within a write transaction, you can add and remove elements to and from a list. Lists are not associated with a query and are usually declared as a property of an object model.

Tip

To learn how to define a to-many relationship, see Define a To-Many Relationship Property.

Relationship definitions in Realm are unidirectional. An inverse relationship links an object back to an object that refers to it. You must explicitly define a property in the object's model as an inverse relationship. Inverse relationships can link back to objects in a to-one or to-many relationship.

A LinkingObjects collection represents the inverse relationship between two Realm types. You cannot directly add or remove items from a LinkingObjects collection.

Inverse relationships automatically update themselves with corresponding backlinks. You can find the same set of Realm objects with a manual query, but the inverse relationship field reduces boilerplate query code and capacity for error.

For example, consider a task tracker with the to-many relationship "User has many Tasks". This does not automatically create the inverse relationship "Task belongs to User". To create the inverse relationship, add a User property on the Task that points back to the task's owner. When you specify the inverse relationship from task to user, you can query on that. If you don't specify the inverse relationship, you must run a separate query to look up the user to whom the task is assigned.

Importante

No se puede establecer manualmente el valor de una propiedad de relación inversa. En su lugar, Realm actualiza las relaciones implícitas cuando se agrega o elimina un objeto en la relación.

Relationships can be many-to-one or many-to-many. So following inverse relationships can result in zero, one, or many objects.

Tip

To learn how to define an inverse relationship, see Define an Inverse Relationship Property.

Volver

Build for tvOS

En esta página