OGeek|极客世界-中国程序员成长平台

标题: ios - 境界- cocoa : How to add notification inside other notification block [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:19
标题: ios - 境界- cocoa : How to add notification inside other notification block

在我的应用中,我注册了一个通知 block ,它本身必须注册另一个通知 block 。

notificationToken = [self.appState.currentProject addNotificationBlock:^(BOOL deleted, NSArray<RLMPropertyChange *> *changes, NSError *error) {
if (deleted) {
    NSLog(@"The object was deleted.");
} else if (error) {
    NSLog(@"An error occurred: %@", error);
} else {
    bool filterChanged = false;
    for (RLMPropertyChange * change in changes){
        if([change.name isEqualToString"filters"])
            filterChanged = true;
    }
    if(filterChanged){
        // compute predicate from filters
        // predicate = [NSPredicate ...
        styles = [Style objectsWithPredicate:predicate]
        notificationTokenStyles = [styles addNotificationBlock:^(RLMResults<Style *> * _Nullable results, RLMCollectionChange * _Nullable change, NSError * _Nullable error) {
            // react on changed styles.
        }]; // <- RLMException here
    }
}];
}
}];

我知道这在技术上是不可能的,但对我来说这是必要的。我可以以某种方式将嵌套的 addNotificationBlock 分派(dispatch)或推迟到另一个线程左右吗?我知道我可以等待 500 毫秒,但这会导致竞争条件。

现在,我的问题是,当我执行导致第一个通知 block 执行的写入事务时,我遇到 RLMException: Cannot register notification blocks from within write transactions. 就在嵌套的 addNotificationBlock。

提前致谢!



Best Answer-推荐答案


这是一个已知问题(参见 this Realm issue on GitHub)。

您可以像这样(Swift 代码)包装新 NotificationToken 的创建:

DispatchQueue.main.async {
    // register observation blocks here
}

或者你可以在开始写事务之前调用realm.refresh()

关于ios - 境界- cocoa : How to add notification inside other notification block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47339378/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4