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 7936673
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T22:17:11+00:00 2026-06-03T22:17:11+00:00

I’m building an app that pulls data from a remote server and stores them

  • 0

I’m building an app that pulls data from a remote server and stores them on a CoreData SQLite database. I’m fetching data from a background thread while the main thread consumes it. Here are the main approaches that I’m using.

  1. All the background threads has its own NSManagedObjectContext.
  2. The persistentStoreCoordinator is shared between the contexts.
  3. On every fetch on the background thread, I save: the inserted objects and reset: the local context.
  4. Using a notification I make the merge with the main thread context.

The problems I’m experiencing:

  • Randomly I’m getting crashes with no messages (NSZombie and Crash Breakpoints are set) on the background threads save: operations.
  • There are lots of duplicated data being generated. The webservice data are for sure ok, so no problem on the server side.

Here goes the code.

The AppDelegate

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Update data from remote server
    WebserviceDataModel *webservice = [[WebserviceDataModel alloc] init];
    webservice.managedObjectContext = self.managedObjectContext;
    [webservice startImport];
}

The background thread fetching and saving data on WebserviceDataModel

- (void)startImport
{
    dispatch_queue_t downloadQueue = dispatch_queue_create("startImport in WebserviceDataModel", NULL);
    dispatch_async(downloadQueue, ^{
        NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
        moc.persistentStoreCoordinator = self.managedObjectContext.persistentStoreCoordinator;

        // get the remote data
        NSDictionary *lojas = [Loja allLojasFromRemoteServer];

        for (NSDictionary *lojaInfo in lojas) {
            Loja *loja __attribute__((unused)) = [Loja lojaWithRemoteData:lojaInfo inManagedObjectContext:moc];
        }

        if ([moc hasChanges]) {
            [moc save:nil];
            [moc reset];
        }
        [moc release];        

    });
    dispatch_release(downloadQueue);
}

The NSManagedObject method for object creation: + (Loja *)lojaWithRemoteData:inManagedContext:

+ (Loja *)lojaWithRemoteData:(NSDictionary *)remoteData inManagedObjectContext:(NSManagedObjectContext *)context
{
    Loja *loja = nil;

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Loja" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"lojaId = %d", [[remoteData objectForKey:@"lojaId"] intValue]];

NSError *error = nil;
loja = [[context executeFetchRequest:request error:&error] lastObject];
[request release];

if (!error && !loja) {
        // create the record
        loja = [NSEntityDescription insertNewObjectForEntityForName:@"Loja" inManagedObjectContext:context];

        loja.lojaId = [remoteData objectForKey:@"lojaId"];
        loja.email = [remoteData objectForKey:@"email"];
        loja.facebook = [remoteData objectForKey:@"facebook"];
        // ... and others...
    }

    return loja;
}

Subscription to the NSManagedObjectContextDidSaveNotification on WebserviceDataModel

- (id)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextChanged:) name:NSManagedObjectContextDidSaveNotification object:nil];
    }
    return self;
}

The contextChanged: method on WebserviceDataModel

- (void)contextChanged:(NSNotification*)notification
{
    if ([notification object] == self.managedObjectContext) return;

    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(contextChanged:) withObject:notification waitUntilDone:YES];
        return;
    }
    [[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
}
  • 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-06-03T22:17:12+00:00Added an answer on June 3, 2026 at 10:17 pm

    Well, I had figured it out. And its working like a charm now. The implementation of multithreaded contexts is correct. The problem was with the applicationDidBecomeActive: My app uses a CoreLocation Fence for a list of features. When the app launches for the first time, the CoreLocation framework show an alert message for the user saying that the app uses de user location… That alert calls applicationDidBecomeActive: again, creating two concurrent waves of updates. Just moved my WebserviceDataModel to a property and implemented a flag to know if its running or not. Thats it

    Just for a final refinement, changed the merge policy to NSMergeByPropertyStoreTrumpMergePolicy, so now the server side data (in memory) wins over the local store.

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

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I have a text area in my form which accepts all possible characters from

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.