[英]iOS Update RLMObject in dispatch_async
I would like to update RLMObject in dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) and get result in dispatch_get_main_queue(), but object updated in other thread is not updated in main ui thread.我想在 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 中更新 RLMObject 并在 dispatch_get_main_queue() 中获得结果,但在其他线程中更新的对象不会在主 ui 线程中更新。 What is solution?
什么是解决方案? Example code is:
示例代码是:
Result is:Age of dogs1: 9Age of dogs2: 9结果是:狗的年龄1:9狗的年龄2:9
but it should be:Age of dogs1: 9Age of dogs2: 11但应该是:狗的年龄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 objectsInRealm:otherRealm 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 objectsInRealm:otherRealm2 where:@"name contains 'Rex2'"];
Dog* dog2 = [otherResults2 firstObject];
NSLog(@"Age of dogs2: %ld", (long)dog2.age);
});
});
如果你在它们各自的调度块的顶部调用[otherRealm refresh]
和[otherRealm2 refresh]
,这将确保给定的领域正在查看数据库中最新的事务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.