在多线程中合并 ManagedobjectContext

发布于 2024-12-19 04:17:01 字数 971 浏览 4 评论 0原文

我的应用程序有主线程,每十秒运行一次并从核心数据读取数据,第二个线程从服务器获取数据并加载到核心数据中。在阅读了一些示例和苹果文档后,我仍然不确定合并的方式是否正确: 1.我为数据库中的每个保存创建新的 ManagedObjectContext 并将其设置为 (appp delegate 中的单个 PersistentStore) 。 2.当我启动在用户视图中加载数据的类时,有以下代码:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
        [nc addObserver:self
               selector:@selector(mergeChanges:)
                   name:NSManagedObjectContextDidSaveNotification
                 object:appDelegate.managedObjectContext];

-(void)mergeChanges:(NSNotification *)notification
{    
    NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];      
    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                  withObject:notification
                               waitUntilDone:YES];  
}

3-从主上下文中的 coredata 读取数据

我想知道这是否正确。 谢谢

My app have main thread which run every ten second and read data from core data and second thread to fetch data from server and load into coredata. after reading some example and also apple document I am still not sure the way i merge is correct:
1. i create new managedObjectContext for each save in database and set it to (single PersistentStore in appp delegate) .
2. have this code when i initate the class for loading data in user view:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
        [nc addObserver:self
               selector:@selector(mergeChanges:)
                   name:NSManagedObjectContextDidSaveNotification
                 object:appDelegate.managedObjectContext];

-(void)mergeChanges:(NSNotification *)notification
{    
    NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];      
    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                  withObject:notification
                               waitUntilDone:YES];  
}

3- read data from coredata from main context

I am wondering if this is correct.
thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文