iphone - 核心数据和线程/Grand Central Dispatch

标签 iphone ios multithreading core-data grand-central-dispatch

我是 Grand Central Dispatch (GCD) 和 Core Data 的初学者,我需要你的帮助才能将 Core Data 与 CGD 结合使用,这样当我向 Core Data 添加 40.000 条记录时,UI 不会被锁定。

我知道 CD 不是线程安全的,所以我必须使用另一个上下文,然后保存数据并合并上下文,据我从一些文章中能够理解。

我还不能做的是将各个部分放在一起。

因此,在我的代码中,我需要您的帮助以了解如何做到这一点。

我有:

/*some other code*/

for (NSDictionary *memberData in arrayWithResult) {

    //get the Activities for this member
    NSArray *arrayWithMemberActivities = [activitiesDict objectForKey:[memberData objectForKey:@"MemberID"]];

    //create the Member, with the NSSet of Activities
    [Members createMemberWithDataFromServer:memberData
                         andActivitiesArray:arrayWithMemberActivities
                              andStaffArray:nil
                           andContactsArray:nil
                     inManagedObjectContext:self.managedObjectContext];
}

我如何将其转换为在后台工作,然后在完成保存后保存数据并更新 UI,而不会在保存 40.000 个对象时阻塞 UI?

最佳答案

这里有一个很好的例子供您尝试。如果您有任何问题,请随时回来:

self.mainThreadContext... // This is a reference to your main thread context
NSPersistentStoreCoordinator *mainThreadContextStoreCoordinator = [self.mainThreadContext persistentStoreCoordinator];
dispatch_queue_t request_queue = dispatch_queue_create("com.yourapp.DescriptionOfMethod", NULL);
dispatch_async(request_queue, ^{

    // Create a new managed object context
    // Set its persistent store coordinator
    NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
    [newMoc setPersistentStoreCoordinator:mainThreadContextStoreCoordinator]];

    // Register for context save changes notification
    NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
    [notify addObserver:self 
               selector:@selector(mergeChanges:) 
                   name:NSManagedObjectContextDidSaveNotification 
                 object:newMoc];

    // Do the work
    // Your method here
    // Call save on context (this will send a save notification and call the method below)
    BOOL success = [newMoc save:&error];
    if (!success)
        // Deal with error
    [newMoc release];
});
dispatch_release(request_queue);

并响应上下文保存通知:

- (void)mergeChanges:(NSNotification*)notification 
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mainThreadContext mergeChangesFromContextDidSaveNotification:notification waitUntilDone:YES];
    });
}

不要忘记在完成后台线程上下文后从通知中心移除观察者。

[[NSNotificationCenter defaultCenter] removeObserver:self];

关于iphone - 核心数据和线程/Grand Central Dispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540801/

相关文章:

ios - 并发(dispatchqueue)测试未按预期进行 ios/swift

c++ - boost::asio 异步条件

iphone - Core Location 和 Core Motion 设备标题

ios - 从设备崩溃日志调试 iPhone 应用程序

ios - 无法在 iOS 的 viewController 中调用 touchesBegan/touchesMoved 方法

ios - 什么时候 View Controller 会成为第一响应者?

c++ - 加载主 QT/QML GUI 窗口会减慢启动画面的渲染速度

iOS - 核心数据集属性主键

iphone - UIScrollView 偶尔会失去弹跳和流畅的滚动

ios - 无法将新创建的 cocoa pod 添加到私有(private) pod 规范