A realm is the core data structure used to organize data in Realm. A realm is a collection of the objects that you use in your application, called Realm objects, as well as additional metadata that describe the objects.
Al abrir un reino, debes especificar un db_config. El db_config Puede contener información como:
An optional path where the realm is stored on device
An optional list of models that the realm should manage
Un programador opcional si necesita personalizar el bucle de ejecución
A
sync_configsi desea utilizar el reino con sincronización de dispositivos
Puede utilizar el constructor predeterminado db_config si no necesita especificar una ruta de archivo de reino, una configuración de sincronización de dispositivo u otros detalles de configuración.
Realm Files
Realm almacena una versión binaria codificada de cada objeto y tipo en un único .realm archivo. Este archivo se encuentra en una ruta específica que se define al abrir el dominio. Se puede abrir, ver y editar el contenido de estos archivos.
Archivos auxiliares
The SDK creates additional files for each realm:
archivos realm, con el sufijo "realm", por ejemplo,
default.realm: contiene datos de objetos.lock files, suffixed with "lock", e.g.
default.realm.lock: keep track of which versions of data in a realm are actively in use. This prevents realm from reclaiming storage space that is still used by a client application.note files, suffixed with "note", e.g.
default.realm.note: enable inter-thread and inter-process notifications.archivos de gestión, con el sufijo "gestión", por
default.realm.managementejemplo: gestión del estado interno.
Realms sincronizados
You can configure a realm to automatically synchronize data between many devices that each have their own local copy of the data. Synced realms need a sync_config and require an Atlas App Services backend to handle the synchronization process.
Las aplicaciones siempre pueden crear, modificar y eliminar objetos de dominio sincronizados localmente, incluso sin conexión. Siempre que haya una conexión de red disponible, el SDK de dominio abre una conexión con un servidor de aplicaciones y sincroniza los cambios con y desde otros clientes. El protocolo Atlas Device Sync y las transformaciones operativas del servidor garantizan que todas las instancias de un dominio completamente sincronizadas vean exactamente los mismos datos, incluso si algunos cambios se produjeron sin conexión o se recibieron fuera de orden.
Synced Realms vs. Non-Synced Realms
Synced realms differ from non-synced local Realm in a few ways:
Synced realms attempt to sync changes with your backend App Services App, whereas non-synced realms do not.
Synced realms can only be accessed by authenticated users, while non-synced realms have no concept of users or authentication.
Con los realms sincronizados, puedes descargar actualizaciones antes de abrir un realm. Sin embargo, exigir que las actualizaciones se descarguen antes de abrir el realm requiere que el usuario esté en línea. Los reinos no sincronizados pueden usarse siempre fuera de línea.
You can manually copy data from a non-synced realm to a synced realm, and vice versa, but you cannot sync a non-synced realm.
Open a Non-Sync Realm
You can open a realm in the current directory using the default constructor. Or you can construct a db_config with a specific file path to open the realm in a specific location.
Open the Default Realm
Opening a realm without specifying an optional path opens the default realm in the current directory.
When opening a realm, the C++ SDK can automatically infer which models are available in the project. You don't need to manually specify the available models unless you are opening a realm to sync data unidirectionally with asymmetric objects. For more information, refer to Open a Synced Realm on this page.
auto config = realm::db_config(); auto realm = realm::db(std::move(config));
Tip
Construyendo una aplicación de Android
When building an Android app that uses the Realm C++ SDK, you must pass the filesDir.path to the path parameter in the db_config constructor. For more information, refer to: Build an Android App.
Abre un Realm en una ruta de archivo
You can use set_path() to specify a path for the db_config to use when opening the realm.
auto relative_realm_path_directory = "custom_path_directory/"; std::filesystem::create_directories(relative_realm_path_directory); // Construct a path std::filesystem::path path = std::filesystem::current_path().append(relative_realm_path_directory); // Add a name for the database file path = path.append("employee_objects"); // Add the .realm extension path = path.replace_extension("realm"); // Set the path on the config, and open the database at the path auto config = realm::db_config(); config.set_path(path); auto realmInstance = realm::db(std::move(config));
Tip
Construyendo una aplicación de Android
Al crear una aplicación Android que utiliza el SDK Realm C++, es necesario pasar el filesDir.path como el parámetro path en el constructor db_config. Para obtener más información, consulta: Construir una aplicación para Android.
Open a Synced Realm
Debe tener una aplicación Atlas App Services que haya configurado para sincronización flexible para poder sincronizar datos entre dispositivos.
To open a synced realm:
Conéctate a una aplicación de Atlas App Services.
Authenticate the user.
Create a sync configuration.
Open the user's synced realm with the configuration.
// Initialize the App, authenticate a user, and open the database auto appConfig = realm::App::configuration(); appConfig.app_id = APP_ID; auto app = realm::App(appConfig); auto user = app.login(realm::App::credentials::anonymous()).get(); auto syncConfig = user.flexible_sync_configuration(); auto syncedRealm = realm::db(syncConfig);
When you open a synced realm, you don't need to pass the models you want the realm to manage into the template parameter list of the open function. This is a change from the deprecated Alpha API.
The only exception to this rule is opening a synced realm to sync asymmetric_object types. When you open a synced realm to sync asymmetric_object types, you must explicitly specify the objects in the template parameter list for the open function. For more information, refer to Stream Data to Atlas - C++ SDK.
Tip
Construyendo una aplicación de Android
When building an Android app that uses the Realm C++ SDK, you must pass the filesDir.path to the path parameter in the db_config constructor. For more information, refer to: Build an Android App.
Set Custom HTTP Headers When Using a Synced Realm
To use custom HTTP headers with Device Sync, you must set the headers on the App and on the flexible_sync_configuration().
After you initialize the configuration, use the set_custom_http_headers() member function to set the custom HTTP headers to a map of string header keys and values.
std::map<std::string, std::string> customHeaders; customHeaders.emplace("CUSTOM_HEADER_NAME", "CUSTOM_HEADER_VALUE"); auto syncConfig = user.flexible_sync_configuration(); syncConfig.set_custom_http_headers(customHeaders);
Now the synced realm can use the headers for all Device Sync network requests.
Provide a Subset of Models to a Realm
Tip
Operating with Low Memory Constraints
Algunas aplicaciones tienen restricciones estrictas de su huella de memoria. Para optimizar el uso de memoria de tu realm en entornos con poca memoria, abre el realm con un subconjunto de modelos.
By default, the C++ SDK automatically adds all object types that have a Object Schema in your executable to your Database Schema.
However, if you want the realm to manage only a subset of models, you can specify those models by passing them into the template parameter list of the realm::open() function.
auto config = realm::db_config(); auto realm = realm::open<realm::Dog>(std::move(config));
Close a Realm
To avoid memory leaks, close the database when you're done using it. Closing the database invalidates any remaining objects. Close the database with db::close().
// Create a database configuration. auto config = realm::db_config(); auto realm = realm::db(config); // Use the database... // ... later, close it. realm.close(); // You can confirm that the database is closed if needed. CHECK(realm.is_closed()); // Objects from the database become invalidated when you close the database. CHECK(specificDog.is_invalidated());