Realm-C++ SDK嵌套对象Schema验证失败问题排查
问题
尝试使用realm-cpp SDK(alpha版本)打开新的Realm数据库文件,定义了包含嵌套对象的Schema:
struct Card : realm::object<Card> { realm::persisted<realm::object_id> _id{realm::object_id::generate()}; realm::persisted<std::string> name; realm::persisted<std::string> question; realm::persisted<std::vector<std::string>> options; static constexpr auto schema = realm::schema("Card", realm::property<&Card::_id, true>("_id"), realm::property<&Card::name>("name"), realm::property<&Card::question>("question"), realm::property<&Card::options>("options") ); }; struct Deck : realm::object<Deck> { realm::persisted<realm::object_id> _id{realm::object_id::generate()}; realm::persisted<std::string> name; realm::persisted<std::vector<Card>> cards; static constexpr auto schema = realm::schema("Deck", realm::property<&Deck::_id, true>("_id"), realm::property<&Deck::name>("name"), realm::property<&Deck::cards>("cards") ); }; auto realm = realm::open<Deck>({dbFile});
移除Deck结构体中的realm::persisted<std::vector<Card>> cards属性时一切正常,但添加该嵌套属性后,抛出运行时异常:
DB: 30017 Thread 0x108a6c580: Open file: ./test.db/realm.db libc++abi: terminating with uncaught exception of type realm::SchemaValidationException: Schema validation failed due to the following errors: - Property 'Deck.cards' of type 'array' has unknown object type 'Card' Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
环境版本:
- realm-cpp sdk alpha
- cmake 3.18.1
- macOS Monterey 12.6.5
- Apple clang version 14.0.0 (clang-1400.0.29.202). Target: arm64-apple-darwin21.6.0.
解决方案
问题核心是打开数据库时仅注册了Deck类型,未注册其依赖的Card类型,导致Realm无法识别Deck.cards属性中的嵌套对象类型。
两种修复方式:
- 在
realm::open中同时指定所有关联类型
// 同时传入Deck和Card类型,让Realm加载所有依赖的Schema auto realm = realm::open<Deck, Card>({dbFile});
- 显式构建包含所有Schema的配置
realm::db_config config{dbFile}; // 将Deck和Card的Schema都加入配置 config.set_schema(realm::schema{Deck::schema, Card::schema}); auto realm = realm::open(std::move(config));
以上两种方式都能让Realm识别Card类型,通过Schema验证。
内容的提问来源于stack exchange,提问作者matt
相关产品推荐
相关产品推荐

