我想更新 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 中的 RLMObject 并在 dispatch_get_main_queue() 中获取结果,但是在其他线程中更新的对象在主 ui 线程中没有更新。什么是解决方案?示例代码为:
结果是:狗的年龄1:9狗的年龄2:9
但应该是:狗的年龄1:9狗的年龄2:11
// Create a standalone object
Dog *mydog = [[Dog alloc] init];
// Set & read properties
mydog.name = @"Rex2";
mydog.age = 9;
NSLog(@"Name of dog: %@", mydog.name);
// Realms are used to group data together
RLMRealm *realm = [RLMRealm defaultRealm]; // Create realm pointing to default file
// Save your object
[realm beginWriteTransaction];
[realm addObject:mydog];
[realm commitWriteTransaction];
// Multi-threading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
RLMRealm *otherRealm = [RLMRealm defaultRealm];
RLMResults *otherResults = [Dog objectsInRealmtherRealm where"name contains 'Rex2'"];
Dog* dog = [otherResults firstObject];
NSLog(@"Age of dogs1: %ld", (long)dog.age);
[otherRealm beginWriteTransaction];
dog.age = 11;
[otherRealm commitWriteTransaction];
dispatch_async(dispatch_get_main_queue(), ^{
RLMRealm *otherRealm2 = [RLMRealm defaultRealm];
RLMResults *otherResults2 = [Dog objectsInRealmtherRealm2 where"name contains 'Rex2'"];
Dog* dog2 = [otherResults2 firstObject];
NSLog(@"Age of dogs2: %ld", (long)dog2.age);
});
});
如果您在各自的调度 block 顶部调用 [otherRealm refresh]
和 [otherRealm2 refresh]
,这将确保给定 Realm 正在查看最多 -数据库中的最新事务。
关于iOS 在 dispatch_async 中更新 RLMObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703603/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |