将 属性 分配给 RLMObject 的子类

Assigning property to subclass of RLMObject

我正在尝试使用 RLMObject 的子class 作为 RLMObject 的其他子class 的 属性 的基础 class,但没有成功.这是已知限制,还是有解决方法?

test.m:

#import <XCTest/XCTest.h>
#import <Realm/Realm.h>

@interface Base : RLMObject; @end
@interface Derived : Base; @end

@interface User : RLMObject
@property Base *obj;
@end

@implementation Base; @end
@implementation Derived; @end
@implementation User; @end

@interface rlmrlmTests : XCTestCase; @end
@implementation rlmrlmTests

- (void) testOK {
    User *user = [[User alloc] init];

    user.obj = [[Base alloc] init]; // OK
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        [[RLMRealm defaultRealm] addObject:user];
    }];
}

- (void) testZFail {
    User *user = [[User alloc] init];

    user.obj = [[Derived alloc] init]; // ERROR
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        [[RLMRealm defaultRealm] addObject:user];
    }];
}

@end

会得到一个异常说:

error: -[rlmrlmTests testZFail] : failed: caught "RLMException", "Can't set object of type 'Derived' to property of type 'Base'"

这是 Realm 的当前限制。就doesn't support polymorphism关系。

如果可能的话,我会在这种情况下避免继承。您可以通过更改对象关系映射来实现:您可以向 Base class 添加一个 discriminator 列并与 class 建立关系es 包含更多属性并且不会再从 Base class 继承。如果你只有一个 subclass,那么最终不需要 discriminator 列。

@interface Base : RLMObject
@property NSString *discriminator;
@property BaseExtensionA *extA;
@property BaseExtensionB *extB;
@end

@interface BaseExtensionA : RLMObject
// the properties of the prior `Derived` would go here
@end

@interface BaseExtensionB : RLMObject
// …
@end