Best practice for long term foreground work that uses Core Data?

I have an application that imports a potentially large amount of data from the Internet after the user explicitly presses the sync button and saves this data using Core Data. Since I want to show feedback, and I don’t want the user to interact with the rest of the application when this happens, clicking the Sync button brings up the Modal dialog. Since I want the operation to be executed immediately, the operation is performed in the viewDidAppear method. I am sure this is disapproving.

Now there are a number of problems with the approach:

  • Everything happens in the main thread. The user type receives feedback because there is an activity indicator that continues to revive, but there is no way to indicate progress or show intermediate messages. This is the wrong way to do something.
    • But I was told that when using Core Data, everything should use the main thread, so disabling the work in another thread does not look like it will be simple.
  • If the application enters the background state (the user presses the "Home" button or the iPad falls asleep), the game ends - the operation dies. It is clear to me from the documentation why this is so.
    • I know that there are events “I'm going to enter the background” that you can handle, but it’s not as if I could move the code from one place to another in the middle of the file upload. No matter which solution I use, there must be a continuous action that is performed in the same way both before and after transitions to / from the background.
    • I want the operation to be performed in the foreground as far as the user is concerned. For them, it makes no sense to interact with other parts of the application during this operation.

I am reading Apple's documentation about this, but I ask for it in the hope of finding more succinct recommendations for this particular mix of needs. Thank.

+3
source share
1 answer

. "" .

, , . ( ), , ... , - ...

NSManagedContext *backgroundContext = [NSManagedContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
backgroudContext.parentContext = [self mainManagedObjectContext];
[backgroundContext performBlock:^{
    // This block is running in a background thread.
    // Go get your data from the web

    // Call this to push data to the main MOC (either at end, or at intervals)
    [backgroundContext save:&error];

    // When you want to do something on the main thread...
    dispatch_async(dispatch_get_main_queue(), ^{
        // This block is running on the main queue... I can do anything with the UI...
    }];
}];

, ... mainMOC concurrency. , , alloc/init initWithConcurrencyType: NSMainQueueConcurrencyType.

/ . MOC, , MOC, private MOC. - , .

, : MOC, MOC.

, , "root" MOC-.

+2

All Articles