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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T08:29:08+00:00 2026-06-15T08:29:08+00:00

I have some code that takes a little time to process and thus appropriately

  • 0

I have some code that takes a little time to process and thus appropriately it should not run on the main queue. However I’m not sure on how to correctly “structure” the GCD code segments. I.e every time the app becomes active I’m doing a syncing operation:

AppDelegate.m

- (void)applicationDidBecomeActive:(UIApplication *)application {

    AddressBookHelper *abHelper = [AddressBookHelper sharedInstance]; // singleton helper class of NSObject

    [abHelper sync];
}

The syncing code inside AddressBookHelper looks something like this:

AddressBookHelper.m

- (void)sync {

    NSArray *people = // Fetching some people from Core Data

    NSMutableArray *syncConflicts;
    // Start doing some business logic, iterating over data and so on

    for (id object in people) {
    // Process some data
        [syncConflicts addObject:object];
    }

    self.syncConflicts = syncConflicts;

    // I have separated this method to keep the code cleaner and to separate the logic of the methods
    [self processSyncConflicts];
}

- (void)processSyncConflicts {

    if ([self.syncConflicts count] > 0) {
        // Alert the user about the sync conflict by showing a UIAlertView to take action
        UIAlertView *alert;
        [alert show];

    } else {

        // Syncing is complete
    }
}

So with this code structure, how would I properly use GCD to put this code on a background thread?

Is it as easy as doing this?

AppDelegate.m

- (void)applicationDidBecomeActive:(UIApplication *)application {

    AddressBookHelper *abHelper = [AddressBookHelper sharedInstance]; // singleton helper class of NSObject

    dispatch_queue_t queue = dispatch_queue_create("addressbookSyncQueue", 0);
    dispatch_async(queue, ^{
            [abHelper sync];
    });
}

AddressBookHelper.m

- (void)processSyncConflicts {

    if ([self.syncConflicts count] > 0) {
        // Alert the user about the sync conflict by showing a UIAlertView to take action
        UIAlertView *alert;
        dispatch_queue_t mainQueue = dispatch_get_main_queue();

        dispatch_async(mainQueue, ^{
            [alert show];
        });

    } else {

        // Syncing is complete
    }
}
  • 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-15T08:29:10+00:00Added an answer on June 15, 2026 at 8:29 am

    I see several potential problems in your code.

    Multiple Simultaneous Syncs

    Suppose you receive applicationDidBecomeActive:, but before [abHelper sync] finishes, the user switches away from your app, and then back to your app. Now you receive another applicationDidBecomeActive:, create a new GCD queue, and start another [abHelper sync] while the first one is still running. Bad!

    Change your AddressBookHelper class to create its own GCD queue and store it in an instance variable. Change the interface so that the sync operation puts itself on that queue. Example:

    @interface AddressBookHelper : NSObject
    
    + (AddressBookHelper *)sharedInstance;
    
    - (void)syncInBackground;
    
    @end
    
    @implementation AddressBookHelper {
        dispatch_queue_t queue_;
    }
    
    - (void)syncInBackground {
        if (!queue_) {
            queue_ = dispatch_queue_create("AddressBookHelper", 0);
        }
        dispatch_async(queue_, ^{ [self syncOnCurrentQueue]; });
    }
    
    - (void)syncOnCurrentQueue {
        // This is now a private method that always runs on queue_.
        // ...
    }
    
    @end
    

    Property Thread-Safety

    I assume your main thread needs to access syncConflicts, since you’re storing it in a property. If so, you should update syncConflicts on the main queue, so that you don’t change it in the middle of some main-queue operation that is using it.

        dispatch_sync(dispatch_get_main_queue(), ^{
            self.syncConflicts = syncConflicts;
        });
    

    Core Data Thread-Safety

    You didn’t show us how you access Core Data. You need to be aware that Core Data objects are not generally thread-safe. Your background sync operation should create a managed object context of its own, as a child of the main managed object context. Then, when the operation is complete, it can tell the child context to save, and the changes will be pushed to the parent context in a thread-safe way.

    Since you’ll be getting your people objects from this child context, you can’t pass them back to the main thread. Instead, you need to store each object’s objectID, and use that to recreate the objects using the main thread’s context.

    - (void)syncOnCurrentQueue {
        // This is now a private method that always runs on queue_.
    
        NSManagedObjectContext *syncContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
        syncContext.parentContext = self.mainContext;
    
        NSArray *people = nil; // Fetching some people from syncContext
    
        NSMutableArray *syncConflictIDs = [[NSMutableArray alloc] init];
        // Start doing some business logic, iterating over data and so on
    
        for (id object in people) {
            // Process some data
            [syncConflictIDs addObject:[object objectID]];
        }
    
        NSError *error;
        if (![syncContext save:&error]) {
            // save to main context failed...
        }
    
        dispatch_sync(dispatch_get_main_queue(), ^{
            // assuming main context has NSMainQueueConcurrencyType
            NSMutableArray *syncConflicts = [[NSMutableArray alloc] initWithCapacity:syncConflictIDs.count];
            for (NSManagedObjectID *objectID in syncConflictIDs) {
                [syncConflicts addObject:[self.mainContext objectWithID:objectID]];
            }
            self.syncConflicts = syncConflicts;
        });
    
        // I have separated this method to keep the code cleaner and to separate the logic of the methods
        [self processSyncConflicts];
    }
    

    UIKit Thread-Safety

    You can only manipulate UIKit objects like UIAlertView on the main thread. You didn’t actually show where you alloc/init your alert view, but I assume you’re not forcing it to be on the main thread given where you declared the variable. You need to make sure you do it on the main thread.

    - (void)processSyncConflicts {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.syncConflicts count] > 0) {
                // Alert the user about the sync conflict by showing a UIAlertView to take action
                UIAlertView *alert = [[UIAlertView alloc] init...];
                [alert show];
            } else {
                // Syncing is complete
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following piece of code that takes in some words, stores them
Does anyone have some code that will take a TimeZoneInfo field from .NET and
I have some code that will change the background color of a specific label
I have some code that is supposed to return an NSString. Instead it is
I have some code that generates Visio masters for me, and some masters have
I have some code that causes the box2d physics simulation to stutter forever after
I have some code that runs a model in a loop. Each iteration of
I have some code that shows results in a table Right now it will
I have some code that uses the SQL Server 2005 SMO objects to backup
I have some code that looks like this: foreach(var obj in collection) { try

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.