【问题标题】:Realm - Can't set object of type subclass to property of type parent class领域 - 无法将子类类型的对象设置为父类类型的属性
【发布时间】:2015-05-15 15:34:08
【问题描述】:

大家好,

我在使用 Realm 时遇到了一个小问题,我有一个类“Contact”和一个子类“Person”,定义为:

人.h

#import <Realm/Realm.h>
#import "Contact.h"

RLM_ARRAY_TYPE(Person)

@interface Person : Contact

@property NSString * nickName;

@end

我有一个名为“Address”的实体,它具有“Contact”属性(地址只能与一个联系人相关)。

地址.h

#import <Realm/Realm.h>
@class Contact;

RLM_ARRAY_TYPE(Address)

@interface Address : RLMObject

@property NSString * city;
@property NSString * country;

@property RLMContact *contact;

@end

问题是:当我尝试将“Person”对象设置为“Address”的联系人属性时,出现此错误:

[address setContact:person];
'Can't set object of type 'Person' to property of type 'Contact'

我尝试投射它,但仍然是同样的问题:

[address setContact:(Contact *)person];
'Can't set object of type 'Person' to property of type 'Contact'

我什至在我的 Address.h 上定义了 Person 类之后尝试过,但仍然是同样的问题:

地址.h

#import <Realm/Realm.h>
@class Contact;
@class Person;

RLM_ARRAY_TYPE(Address)

@interface Address : RLMObject

@property NSString * city;
@property NSString * country;

@property RLMContact *contact;

@end

有人有想法吗?

提前谢谢各位。

【问题讨论】:

    标签: realm


    【解决方案1】:

    在 Realm 中,虽然您可以对 RLMObject 实体进行子类化,但这些子类不是多态的。也就是说,当你说你正在链接到 Contact 对象时,你不能替换 Person 对象,因为 Realm 将它们视为完全独立的实体。

    【讨论】:

    • 再次感谢 segiddins !
    • 我会说这是一个相当大的失败点,它位于面向对象的语言之上,尤其是对于更复杂的数据库。这可以被认为是一项功能吗?
    • 我们打算在未来引入某种多态性,但这需要对底层数据库引擎进行重大更改。您可以关注github.com/realm/realm-cocoa/issues/1109 以获取更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多