代码之家  ›  专栏  ›  技术社区  ›  SaintTail

如何在领域事务完成后触发KVO?

  •  0
  • SaintTail  · 技术社区  · 8 年前

    我有模型,它是 Group Thread 它们的关系如下:

    一对多 线

    我有这个代码,当离开组时会触发

    [RLMRealm transactionWithBlock:^(RLMRealm *realm) {
        // Clear all unread in threads
        RLMResults<Thread *> *threads = [Thread allThreadsInGroupID:self._id];
        for (Thread *thread in threads) {
            [thread clearLocalUnreads]; // <-- Trigger KVO for thread
        }
    
        // Delete group
        [realm deleteObject:self];
    } error:nil];
    

    ViewController 我使用 KVO 线 并在发生更改时调用此方法

    - (void)threadsControllerDidReloadData:(ThreadsController *)controller {
    
        // To prevent realm notification infinite loop in WorkspaceKPIDatasource
        if ([self.tableView.dataSource isKindOfClass:[WorkspaceTableViewController class]]) {
            WorkspaceTableViewController *workspaceTVC = (WorkspaceTableViewController *)self.tableView.dataSource;
            if ([workspaceTVC.contentDatasource isKindOfClass:[WorkspaceThreadsDatasource class]]) {
                [self.tableView reloadData];
    
                // Fix crash when reloadData is try to access group during leave since calling reloadData, the update
                // will not happen immediately. This line will force the layout to update immediately result in calling
                // - cellForRowAtIndexPath in the same run loop to prevent accessing invalidate group
                [self.tableView.superview layoutIfNeeded]; // <-- This solve crash
            }
            [workspaceTVC refreshHeader];
        }
    }
    

    这里有两个问题

    1. KVO是在领域事务未完成的情况下触发的
    2. cellForRowAtIndexPath 打电话后 reloadData 不会立即运行,即使 在删除组之前触发,当单元格处于布局时,它会崩溃。为什么尝试访问无效组。

    我现在选择选项2来克服这个问题,因为它最简单。 但我认为更合理的方法是让 KVO 仅在事务完成后触发。在这种情况下,无论事务中发生什么,都将在最后进行分组。

    因为这个问题,我认为 KVO 对于领域来说,可能会导致一些问题,比如事务在中途失败,但不知何故 KVO 由于对象级别的更改,已触发。

    而是通过阅读文件 here .在我看来 KVO 将在写入事务发生时调用,但我不知道为什么,在我的情况下,何时调用 线 已更新,并且 - threadsControllerDidReloadData: 叫做为什么 [group isInvalidated] 仍然返回 NO 用那种方法

    1 回复  |  直到 8 年前
        1
  •  1
  •   TiM    8 年前

    从听起来,KVO可能不适合您想要完成的任务。

    如果您正在与表视图中的数据交互,则使用 Realm's fine-grained notifications 注册更改。该系统设计用于处理表视图,并将在更适合更新表视图内容的时间延迟和发送通知。