realm-swift icon indicating copy to clipboard operation
realm-swift copied to clipboard

RLMThreadSafeReference + non default RLMRealm instance

Open stephenkopylov opened this issue 8 years ago • 4 comments
trafficstars

Hello guys and thank you for Realm!

Goals

In my project, I have two instances of RLMRealm - primary and secondary and I have instances of Foo-object in both databases. So now I want to pass thread safe reference of Foo-object to the method, in which it's unknow which realm was used to store object.

I've found "realm" property in "RLMThreadConfined", but it's not accessible from public. Is it possible to recognise which realm was used to store RLMObject, referenced by RLMThreadSafeReference, without passing RLMRealm into method?

Code Sample

-(void)test{
	RLMRealm *realm1 = [RLMRealm realmWithConfiguration:config1];

	RLMRealm *realm2 = [RLMRealm realmWithConfiguration:config2];

	Foo *foo1 = [Foo objectsInRealm:realm1 where:@""][0];

	Foo *foo2 = [Foo objectsInRealm:realm2 where:@""][0];

	[self handleFoo:[RLMThreadSafeReference referenceWithThreadConfined:foo1]];

	[self handleFoo:[RLMThreadSafeReference referenceWithThreadConfined:foo2]];
}

-(void)handleFoo:(RLMThreadSafeReference*)ref{
    Foo *foo = [[RLMRealm defaultRealm] resolveThreadSafeReference:ref]; //obvious exception, with object, stored in non-default db
}

stephenkopylov avatar Aug 07 '17 10:08 stephenkopylov

The simplest solution is to pass the configuration along with the thread safe reference, so you can resolve the reference in the appropriate Realm:

-(void)test{
    RLMRealm *realm1 = [RLMRealm realmWithConfiguration:config1];

    RLMRealm *realm2 = [RLMRealm realmWithConfiguration:config2];

    Foo *foo1 = [Foo objectsInRealm:realm1 where:@""][0];

    Foo *foo2 = [Foo objectsInRealm:realm2 where:@""][0];

    [self handleFoo:[RLMThreadSafeReference referenceWithThreadConfined:foo1] configuration:config1];

    [self handleFoo:[RLMThreadSafeReference referenceWithThreadConfined:foo2] configuration:config2];
}

-(void)handleFoo:(RLMThreadSafeReference*)ref configuration:(RLMRealmConfiguration *)config{
    Foo *foo = [[RLMRealm realmWithConfiguration:config] resolveThreadSafeReference:ref];
}

bdash avatar Aug 07 '17 17:08 bdash

@bdash thank you! I'll make a small wrapper around RLMThreadSafeRefence to keep configuration inside the object, but Is it possible to add property with configuration into RLMThreadSafeReference in future releases?

stephenkopylov avatar Aug 08 '17 04:08 stephenkopylov

I've made a small wrapper around RLMThreadSafeRefence, that keeps configuration inside https://github.com/stephenkopylov/SKThreadSafeReference

But anyway, IMHO it would be very useful to keep RLMRealmConfiguration into RLMThreadSafeRefence

stephenkopylov avatar Aug 08 '17 11:08 stephenkopylov

You make a good point. We'll look to make this available in the future.

bdash avatar Aug 16 '17 06:08 bdash