Core Data multi-thread management through GCD, coregcd

Source: Internet
Author: User

Core Data multi-thread management through GCD, coregcd

For a time-consuming database operation, we can adopt multithreading to avoid blocking the UI thread. The complete code in this article can be downloaded here

Multi-thread operations of Core Data mainly involve two problems.

1. How to use multithreading?
2. How do I notify the main thread of updates in the subthread?

There are many similar tutorials on the Internet, so I will not elaborate on them here. The main idea is that NSManagedObjectContext is NOT thread-safe, while NSPersistentStoreCoordinator is thread-safe.

Therefore, when we need to perform CRUD in the Child thread, we need to create an NSManagedObjectContext and reuse the previous NSPersistentStoreCoordinator. Therefore, NSPersistentStoreCoordinator is more like a singleton class.

In Xcode 6.3, check the application created by Core Data. The Basic Code of Core Data has been implemented in AppDelegate. Because AppDelegate is a singleton class, when you need to use the NSPersistentStoreCoordinator class object, you can simply use AppDelegate.

The relationship between the two is clearly explained by directly stealing images from the official website of apple.

The following code demonstrates how to use multiple threads for CRUD operations.

- (void)viewDidLoad {    [super viewDidLoad];    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;    [delegate.managedObjectContext insertTeamWithName:@"Heat"city:@"Miami"];    [delegate.managedObjectContext insertTeamWithName:@"Lakers"city:@"LA"];    [delegate.managedObjectContext insertTeamWithName:@"Thunder"city:@"Oklahoma"];    [delegate saveContext];    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];        [tmpContext setPersistentStoreCoordinator:delegate.persistentStoreCoordinator];        [tmpContext insertTeamWithName:@"76ers" city:@"Philadelphia"];        [tmpContext saveContext];        NSLog(@"%@",[NSThread currentThread]);        dispatch_async(dispatch_get_main_queue(), ^{            NSLog(@"%@",[NSThread currentThread]);            self.teamArray = [delegate.managedObjectContext fetchTeamList];            if (self.teamArray) {                for (Team *teamObject in self.teamArray) {                    NSLog(@"Team info : %@, %@\n", teamObject.name, teamObject.city);                }              }        });    });}

Note that the insertTeamWithName method is implemented in the extension of NSManagedObjectContext. This is not implemented in AppDelegate because the created temporary NSManagedObjectContext object can also call these methods. At the same time, the user-oriented CRUD operation only needs to know the NSManagedObjectContext object immediately, the underlying implementation is not concerned.

To synchronize data in the main thread and sub-thread, we also need to use a notification. Notify the main thread of context update when saveContext is saved.
The following code is implemented in Appdelegate. m.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];- (void)mocDidSaveNotification:(NSNotification *)notification{    NSManagedObjectContext *savedContext = [notification object];    if (savedContext == self.managedObjectContext) {        return ;    }    if (savedContext.persistentStoreCoordinator != self.persistentStoreCoordinator) {        return ;    }    dispatch_async(dispatch_get_main_queue(), ^{        NSLog(@"Merge changes from other context.\n");        [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];    });}

In the mocDidSaveNotification method, there are two if judgments. The first judgment ensures that you do not merge your own updates. The second Judgment aims, if an App uses more than one set of context (for example, a set of context is responsible for student, score, and other business-related information. Another set of context is responsible for the app's own information). One context does not merge the information of another set of context.

The output is as follows:

2015-06-22 22:31:27.680 MultiThreadCoreData[4369:3916642] <NSThread: 0x7fb13b6117b0>{number = 2, name = (null)}2015-06-22 22:31:27.722 MultiThreadCoreData[4369:3916522] Merge changes from other context.2015-06-22 22:31:27.723 MultiThreadCoreData[4369:3916522] <NSThread: 0x7fb13b608220>{number = 1, name = main}2015-06-22 22:31:27.724 MultiThreadCoreData[4369:3916522] Team info : 76ers, Philadelphia2015-06-22 22:31:27.724 MultiThreadCoreData[4369:3916522] Team info : Heat, Miami2015-06-22 22:31:27.724 MultiThreadCoreData[4369:3916522] Team info : Lakers, LA2015-06-22 22:31:27.724 MultiThreadCoreData[4369:3916522] Team info : Thunder, Oklahoma

We can see that the added data in the Child thread is successfully saved, and the context of the main thread updates the data in a timely manner.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.