问题描述
请放心,我已经看到了相同问题的所有答案.按照此链接输入switch-from-local-to-synced-realm
Be assured I have seen all the answer for the very same questions .following this link enter switch-from-local-to-synced-realm
我有一个本地域,我想从该域复制到同步域.
I have a local realm from where I want to copy to synced realm .
public void InitiateSyncForPost() { realm = Realm.GetInstance(ConfigForSync); //realm.WriteAsync((Realm obj) => //{ // var realmOld = Realm.GetInstance(Config); // var ding = realmOld.All<Post>().ToList(); // var dang = realmOld.All<Comment>().ToList(); // var ting = realmOld.All<ImageData>().ToList(); // foreach (var t in dang) // { // obj.Add(t, false); // } // foreach (var t in ding) // { // obj.Add(t, false); // } //foreach (var t in ting) // { // obj.Add(t, false); // } //}); realm.Write(() => { var realmOld = Realm.GetInstance(Config); var ding = realmOld.All<Post>().ToList(); var dang = realmOld.All<Comment>().ToList(); var ting = realmOld.All<ImageData>().ToList(); realmOld.Dispose(); foreach (var t in ting) { realm.Add(t, true); } foreach (var t in dang) { realm.Add(t, true); } foreach (var t in ding) { realm.Add(t, true); } }); }
如您所见,我同时尝试了异步write和write方法.两者都给我例外
as you can see I tried both async write and write method .both are giving me exception
当我使用WriteAsync
我遇到异常,例如条件未满足数组长度== 1(不完全记得)
When I am using WriteAsync
I get exception something like condition not met array length == 1 (don't exactly remember )
使用当前代码时,出现此异常
When I am using current code I am getting this exception
Realms.Exceptions.RealmObjectManagedByAnotherRealmException:如果对象已由另一个领域管理,则无法开始管理该领域的对象
将对象从本地域复制到同步域时,我做错什么了吗?
Is there anything wrong I am doing in copying the object from local realm to synced realm ?
推荐答案
您需要先创建>子类的非托管副本,然后再将其添加到新的领域.
You need to create a non-managed copy of your RealmObject subsclass before adding it to the new Realm.
您可以手动执行此操作,也可以通过辅助扩展程序执行此操作.
You can do this manually or via a helper extension.
var nonSyncedRealm = Realm.GetInstance(nonSyncedRealmConfig); var syncedRealm = Realm.GetInstance(syncedRealmConfig); var nonSyncedAll = nonSyncedRealm.All<ARealmClass>(); syncedRealm.Write(() => { foreach (var realmObject in nonSyncedAll) { var syncedObject = realmObject.NonManagedCopy<ARealmClass>(); syncedRealm.Add(syncedObject, true); } });
手册副本:
将RealmObject子类的每个属性分配给新实例的非托管对象.
Manual Copy:
Assign each property of your RealmObject subclass to a newly instanced non-managed object.
syncedRealm.Write(() => { foreach (var realmObject in nonSyncedAll) { var syncedObject = new ARealmClass { Id = realmObject.Id, Name = realmObject.Name, ~~~~~~ ~~~~~~ ~~~~~~ ~~~~~~ }; syncedRealm.Add(syncedObject, true); } });
( 1 )免责声明RealmJson.Extensions是我编写的扩展,可通过nuget软件包或源提供:
(1) Disclaimer RealmJson.Extensions is an extension I wrote, available via nuget package or source:
re: https://sushihangover.github.io/Realm.Json.Extensions/
这篇关于在Xamarin.iOS中将本地领域转换为同步领域时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!