Docs Menu

빠른 시작 - C++ SDK

이 빠른 시작에서는 Realm C++ SDK 와 함께 Realm 을 사용하는 방법을 보여줍니다. 시작하기 전에 C++ SDK 를 설치했는지 확인하세요.

사용하려는 번역 단위에 cpprealm/sdk.hpp 헤더를 포함하여 코드에서 Realm C++ SDK를 사용할 수 있도록 합니다.

#include <cpprealm/sdk.hpp>

로컬 전용 영역 의 경우 코드에서 직접 객체 모델 을 정의할 수 있습니다. 이 빠른 시작에서는 선택적 Device Sync 를 추가하지 않는 한 ownerId 를 제거 할 수 있습니다.

namespace realm {
struct Todo {
realm::primary_key<realm::object_id> _id{realm::object_id::generate()};
std::string name;
std::string status;
// The ownerId property stores the user.identifier() of a
// logged-in user. Omit this property for the non-sync example.
std::string ownerId;
};
REALM_SCHEMA(Todo, _id, name, status, ownerId);
} // namespace realm

Realm 을 열 때 영역 를 지정해야 합니다. 선택적으로 특정 경로에서 영역 을 열거나 sync_config 를 제공하여 동기화된 영역 을 열 수 있습니다.

auto config = realm::db_config();
auto realm = realm::db(std::move(config));

자세한 내용은 Realm 구성 및 열기를 참조하세요.

영역을 열고 나면 쓰기 트랜잭션(write transaction) 블록에서 영역과 해당 객체를 수정할 수 있습니다.

새 Todo 객체 를 인스턴스화하고 쓰기 (write) 차단 의 영역 에 추가하려면 다음을 수행합니다.

auto todo = realm::Todo{.name = "Create my first todo item",
.status = "In Progress"};
realm.write([&] { realm.add(std::move(todo)); });

Realm에 있는 모든 할 일의 실시간 결과 컬렉션 을 검색할 수 있습니다.

auto todos = realm.objects<realm::Todo>();

where를 사용하여 해당 컬렉션을 필터링할 수도 있습니다.

auto todosInProgress = todos.where(
[](auto const& todo) { return todo.status == "In Progress"; });

todo를 수정하려면 쓰기 트랜잭션(write transaction) 차단에서 속성을 업데이트합니다.

auto todoToUpdate = todosInProgress[0];
realm.write([&] { todoToUpdate.status = "Complete"; });

마지막으로 할 일을 삭제할 수 있습니다:

realm.write([&] { realm.remove(specificTodo); });

observe 메서드를 사용하여 객체 의 변경 사항 을 관찰할 수 있습니다.

auto token = specificTodo.observe([&](auto&& change) {
try {
if (change.error) {
rethrow_exception(change.error);
}
if (change.is_deleted) {
std::cout << "The object was deleted.\n";
} else {
for (auto& propertyChange : change.property_changes) {
std::cout << "The object's " << propertyChange.name
<< " property has changed.\n";
}
}
} catch (std::exception const& e) {
std::cerr << "Error: " << e.what() << "\n";
}
});

영역 을 닫고 모든 기본 리소스를 출시하다 하려면 db::close() 를 호출합니다. 데이터베이스 를 닫으면 나머지 객체가 무효화됩니다.

realm.close();

여러 기기에서 Realm 데이터를 동기화 하려면 Atlas App Services 앱을 설정하다 하고 Device Sync 를 활성화 됩니다. App Services 로 수행할 수 있는 작업에 대한 자세한 내용은 애플리케이션 서비스 - C++ SDK 를 참조하세요.

Realm 데이터를 동기화하려면 먼저 다음을 수행해야 합니다.

인증 및 동기화와 같은 App Services 기능을 사용하려면 앱 ID를 사용하여 App Services 앱에 액세스합니다. App Services UI에서 앱 ID 찾기를 수행할 수 있습니다.

auto appConfig = realm::App::configuration();
appConfig.app_id = APP_ID;
auto app = realm::App(appConfig);

이 빠른 시작에서는 익명 인증을 사용하여 사용자가 식별 정보를 제공하지 않고도 로그인할 수 있습니다. 사용자를 인증한 후 해당 사용자에 대한 영역을 열 수 있습니다.

auto user = app.login(realm::App::credentials::anonymous()).get();

Realm C++ SDK 는 사용자를 인증, 등록, 연결할 수 있는 다양한 추가 방법을 제공합니다. 다른 인증 제공자에 대해서는 사용자 인증 - C++ SDK를 참조하세요.

Device Sync 를 활성화하고 사용자를 인증한 후에는 sync_configuration 객체 를 생성하고 영역 을 열 수 있습니다. 그런 다음 영역 에서 읽고 쓰기 (write) 수 있는 데이터를 결정하는 Flexible Sync 구독 을 추가할 수 있습니다.

auto syncConfig = user.flexible_sync_configuration();
auto realm = realm::db(syncConfig);
// For this example, get the userId for the Flexible Sync query
auto userId = user.identifier();
auto subscriptions = realm.subscriptions();
auto updateSubscriptionSuccess =
subscriptions
.update([&](realm::mutable_sync_subscription_set& subs) {
subs.add<realm::Todo>("todos", [&userId](auto& obj) {
// For this example, get only Todo items where the ownerId
// property value is equal to the userId of the logged-in user.
return obj.ownerId == userId;
});
})
.get();

동기화된 영역에서 변경 사항을 읽고, 쓰고, 보는 구문은 위의 동기화되지 않은 영역의 구문과 동일합니다.

여기서 유일한 차이점은 이 예제에서는 로그인한 사용자의 user.identifier()Todo 항목의 ownerId 속성에 저장한다는 것입니다. 이렇게 하면 구독에서 사용자의 할 일만 쿼리하고 동기화 권한을 Users can only read and write their own data 로 설정할 수 있습니다.

동기화 권한에 대한 자세한 내용은 역할 기반 권한을 참조하세요.

auto todo = realm::Todo{.name = "Create a Sync todo item",
.status = "In Progress",
.ownerId = userId};
realm.write([&] { realm.add(std::move(todo)); });
auto todos = realm.objects<realm::Todo>();

로컬 데이터로 작업하는 동안 백그라운드 스레드는 변경 세트를 효율적으로 통합, 업로드 및 다운로드합니다.

구독 세트에 대한 모든 쓰기 트랜잭션(write transaction)에는 성능이 소모됩니다. 세션 중에 영역 객체를 여러 번 업데이트해야 하는 경우 모든 변경이 완료될 때까지 편집한 객체를 메모리에 보관하는 것이 좋습니다. 이렇게 하면 모든 변경 사항 대신 완전하고 업데이트된 객체만 영역에 기록하므로 동기화 성능이 향상됩니다.