示例:
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后,答案 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
}