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

标题: ios - WatchKit 和 App 之间的 Core Data 实时同步 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:49
标题: ios - WatchKit 和 App 之间的 Core Data 实时同步

我正在为 iPhone 应用程序编写 WatchKit 扩展。我使用 App Groups 共享核心数据。这是有效的,数据是共享的。现在,如果应用程序在前台运行并且新的数据库条目从 watch 添加到数据库,我想刷新 iPhone 应用程序内的数据。跟踪我订阅了 NSManagedObjectContextDidSaveNotification

[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selectorselector(mergeChanges
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:nil];
        }
    }

合并方法:

- (void)mergeChangesNSNotification *)notification {
    if(notification.object != self.managedObjectContext) {
        [self performSelectorOnMainThreadselector(updateMainContext withObject:notification waitUntilDone:NO];
    }
}

更新主上下文方法:

- (void)updateMainContextNSNotification *)notification {
    assert([NSThread isMainThread]);
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

我试图在模拟器上测试它(通过同时运行 iPhone 和 Watch 模拟器),但不幸的是 NSManagedObjectContextDidSaveNotification 没有被调用。

真的可以在模拟器上测试吗?如果是,这是正确的方法吗?



Best Answer-推荐答案


您不能使用 NSNotificationCenter,因为 iOS 应用程序和扩展程序是不同的进程。查看使用 MMWormhole 在进程之间发布您自己的通知。您可以在您的扩展程序和 iOS 应用程序中监听 NSManagedObjectContextDidSaveNotification,然后使用 MMWormhole 让其他进程知道通知。此外,您还需要手动刷新托管数据对象(参见 [NSManagedObjectContext refreshObjectNSManagedObject *)object mergeChangesBOOL)flag])。

关于ios - WatchKit 和 App 之间的 Core Data 实时同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265905/






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