iOS 在 dispatch_async 中更新 RLMObject

iOS Update RLMObject in dispatch_async

我想更新 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 中的 RLMObject 并在 dispatch_get_main_queue() 中获取结果,但是在其他线程中更新的对象在主 ui线程。什么是解决方案?示例代码是:

结果 is:Age of dogs1: 9Age of dogs2: 9

但它应该 be:Age of dogs1: 9Age of dogs2: 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],这将确保给定领域正在查看数据库中的最新事务。