2

我有需要迭代的 RLMResults,执行一个可能“长时间运行”的下载任务(足够长,它不应该在主线程上),并使用此下载的结果更新每个对象。我尝试过的最新迭代(在搜索文档以获得答案之后)是这样的,虽然这显然不能按预期工作,但它是演示目的的起点:

RLMResults *objectsToSaveImagesFor = [self allObjectsToSaveImagesFor];
for (Object *object in objectsToSaveImagesFor) {
    RLMThreadSafeReference *objectRef = [RLMThreadSafeReference referenceWithThreadConfined:object];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        RLMRealm *realm = [RLMRealm realmWithConfiguration:self.realm.configuration error:nil];

        Object *threadSafeObject = [realm resolveThreadSafeReference:objectRef];

        BOOL success = [self downloadImageForObject:threadSafeObject];

        [realm transactionWithBlock:^{
            threadSafeObject.imageSaved = success;
        }];
    });
}

我已经尝试了十多次迭代,但无法找出规范的 Realm 方法来做我想做的事情,即下载大量图像(数千张)并更新我的每一个具有后台线程下载结果的领域对象。

4

1 回答 1

2

无需为 中的每个对象创建和解析线程安全引用RLMResults,只需执行一次:

RLMResults *objectsToSaveImagesFor = [self allObjectsToSaveImagesFor];
RLMThreadSafeReference *objectsRef = [RLMThreadSafeReference referenceWithThreadConfined:objectsToSaveImagesFor];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    RLMRealm *realm = [RLMRealm realmWithConfiguration:self.realm.configuration error:nil];
    RLMResults *objectsToSaveImagesFor2 = [realm resolveThreadSafeReference:objectsRef];
    for (Object *object in objectsToSaveImagesFor2) {
      BOOL success = [self downloadImageForObject:threadSafeObject];
      [realm transactionWithBlock:^{
        object.imageSaved = success;
      }];
    }
});
于 2017-03-13T21:42:53.630 回答