当使用多个领域时,如何停止出现在0个实例的所有领域中的所有类?

时间:2018-05-25 08:19:50

标签: ios objective-c realm

示例:

2领域:Blue.realm,Red.realm

2个RLMObject子类:BlueClass,RedClass。

我创建并向Blue.realm添加一个BlueClass实例,我创建RedClass实例并将其添加到Red.realm。

当我在Realm Studio中查看领域及其内容时,我看到了:

Blue.realm

BlueClass(1)

RedClass(0)

Red.realm

BlueClass(0)

RedClass(1)

实例化的实例位于正确的领域,但所有其他领域类都被添加到每个领域,内容为0。

我确信某处必须有一个简单的解决办法,但我找不到它。

-(void)runRealmTests{

NSURL *defaultURL = [RLMRealmConfiguration defaultConfiguration].fileURL;
NSLog(@"FILEURL: %@",defaultURL);

NSError *error;
RLMRealmConfiguration *redConfig = [RLMRealmConfiguration defaultConfiguration];
redConfig.fileURL = [[defaultURL URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"red.realm"];
RLMRealm *redRealm = [RLMRealm realmWithConfiguration:redConfig error:&error];
if (redRealm == nil) {
    NSLog(@"ERROR: %@",error.localizedDescription);
    return;
}
RedClass *red = [[RedClass alloc]init];
red.date = [NSDate date];
[redRealm beginWriteTransaction];
[redRealm addObject:red];
BOOL success = [redRealm commitWriteTransaction:&error];
if (!success) {
    NSLog(@"ERROR: %@",error.localizedDescription);
    return;
}

RLMRealmConfiguration *blueConfig = [RLMRealmConfiguration defaultConfiguration];
blueConfig.fileURL = [[defaultURL URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"blue.realm"];
RLMRealm *blueRealm = [RLMRealm realmWithConfiguration:blueConfig error:&error];
if (blueRealm == nil) {
    NSLog(@"ERROR: %@",error.localizedDescription);
    return;
}
BlueClass *blue = [[BlueClass alloc]init];
blue.date = [NSDate date];
[blueRealm beginWriteTransaction];
[blueRealm addObject:blue];
success = [blueRealm commitWriteTransaction:&error];
if (!success) {
    NSLog(@"ERROR: %@",error.localizedDescription);
    return;
}

}

创建一个RedClass和一个BlueClass后,

red.realm red.realm after creating one RedClass and one BlueClass 创建一个RedClass和一个BlueClass后, blue.realm blue.realm after creating one RedClass and one BlueClass

1 个答案:

答案 0 :(得分:1)

您需要创建两个单独的Realm.Configuration实例,并使用指定哪个Realm子类应属于哪个域的不同配置创建两个Object。默认配置包括两个领域中的所有Object子类,因此存在问题。

let blueConfig = Realm.Configuration(fileURL: blueURL, inMemoryIdentifier: "blueRealm", schemaVersion: 1, migrationBlock: nil, objectTypes: [BlueClass.self])
let redConfig = Realm.Configuration(fileURL: redURL, inMemoryIdentifier: "redRealm", schemaVersion: 1, migrationBlock: nil, objectTypes: [RedClass.self])    
do {
    let blueRealm = try Realm(configuration: blueConfig)
    let redRealm = try Realm(configuration: redConfig)
} catch {
    print(error)
    // handle the error correctly
}