gpt4 book ai didi

iOS 在 dispatch_async 中更新 RLMObject

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:58:33 26 4
gpt4 key购买 nike

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

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

但应该是: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);
});
});

最佳答案

如果你在它们各自的调度 block 的顶部调用 [otherRealm refresh][otherRealm2 refresh],这将确保给定的 Realm 正在寻找最多 -数据库中的最新交易。

关于iOS 在 dispatch_async 中更新 RLMObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com