Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7068993
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:23:30+00:00 2026-05-28T05:23:30+00:00

In my App I am fetching requests with JSON content, parsing them and storing

  • 0

In my App I am fetching requests with JSON content, parsing them and storing them in CoreData. In the same time the user is interacting with the DB (reading and writing access).

After storing data to the DB a second task is started that create new data, based on the received data. Im going to use Grand Central Dispatch to do the parsing and storing the data to the DB.

My problem is that when using GCD I get a EXC_BAD_ACCESS which could me caused of the non thread safety of Core Data I assume. An other error is that I get a deadlock when using context performBlockAndWait.

How should I design my app that has a proper handling of GCD and NSMutableContexts?

——-EDIT——–

Now that I have read the core data programming guide I cam to the point that I have to use the Thread Confinement Pattern.

My App is currently structured this way: I have a couple of Managers that each hold their own context. But when using several threads I come to the point where 3 threads call the same Manager which means that one context is used by 3 threads simultaneously. This results in a deadlock.

To solve this I came to the idea to create a context by threadname like this:

- (NSManagedObjectContext *)createManagedObjectContextWithTreadName:(NSString*) threadname {

    if([NSThread currentThread].name.length ==0){
        [NSThread currentThread].name = threadname; 
    }

    NSManagedObjectContext *context = nil;
    context = [self.contextStore objectForKey:threadname];

    if(!context){
        NSLog(@"Creating context for threadname: %@",threadname);

        NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
        if (coordinator != nil)
        {
            context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
            context.persistentStoreCoordinator = coordinator;
            context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy;

            NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
            [nc addObserver:self selector:@selector(mergeChangesFromMOC:) name:NSManagedObjectContextDidSaveNotification object:context];
            [self.contextStore setValue:context forKey:threadname];
        }
    }
    return context;
}

Is this a good idea?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T05:23:31+00:00Added an answer on May 28, 2026 at 5:23 am

    Ok – here is how I solved it:

    +(NSManagedObjectContext *)managedObjectContext {
        AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        NSManagedObjectContext *moc = delegate.managedObjectContext;
    
        NSThread *thread = [NSThread currentThread];
    
        if ([thread isMainThread]) {
            return moc;
        }
    
        // a key to cache the context for the given thread
        NSString *threadKey = [NSString stringWithFormat:@"%p", thread];
    
        // delegate.managedObjectContexts is a mutable dictionary in the app delegate
        NSMutableDictionary *managedObjectContexts = delegate.managedObjectContexts;
    
        if ( [managedObjectContexts objectForKey:threadKey] == nil ) {
            // create a context for this thread
            NSManagedObjectContext *threadContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
    
            threadContext.persistentStoreCoordinator = [moc persistentStoreCoordinator];
            threadContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy;
    
            NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
            [nc addObserver:self selector:@selector(mergeChangesFromMOC:) name:NSManagedObjectContextDidSaveNotification object:threadContext];
    
            // cache the context for this thread
            [managedObjectContexts setObject:threadContext forKey:threadKey];
            //NSLog(@"MocCount: %d",managedObjectContexts.count);
        }
    
        return [managedObjectContexts objectForKey:threadKey];
    }
    
    + (void)mergeChangesFromMOC:(NSNotification *)aNotification {
    
        //NSLog(@"Performing a merge of managed object context in class %@",[self class]);
    
        @try {
            AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
            NSManagedObjectContext *moc = delegate.managedObjectContext;
            [moc mergeChangesFromContextDidSaveNotification:aNotification];
    
    
            NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
            [nc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:[aNotification object]];      
        }
        @catch (NSException * e) {
            NSLog(@"Stopping on exception: %@", [e description]);
        }
        @finally {}
    }
    

    Anywhere I need a context, I ask [ContainingClass managedObjectContext] and get the context for the main thread or the thread I am in. When a merge is needed this is performed on the main thread.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am developing facebook app in which i am fetching user's friend detail in
What is the preferred method of fetching a url and it's content in app-engine?
I am creating a mobile app using jquery mobile, PHP using JSON for fetching
So I'm fetching a JSON string from a php script in my iPhone app
In iOS I need to call same method number of time, but the app
I have an App using UITableViews and fetching data from a server. I am
In my rails app the model is fetching some XML and returning an array.
I have created a class for fetching server-side data in my iOS-App, based on
My app has a UISearchBar allowing user to enter search keywords. Each keystroke executes
how to get size of entity in google app engine without fetching the entity

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.