Note that there are some explanatory texts on larger screens.

plurals
  1. POGraceful termination of NSApplication with Core Data and Grand Central Dispatch (GCD)
    primarykey
    data
    text
    <p>I have an Cocoa Application (Mac OS X SDK 10.7) that is performing some processes via Grand Central Dispatch (GCD). These processes are manipulating some Core Data NSManagedObjects (non-document-based) in a manner that I believe is thread safe (creating a new managedObjectContext for use in this thread). </p> <p><strong>The problem</strong> I have is when the user tries to quit the application while the dispatch queue is still running.</p> <p>The NSApplication delegate is being called before actually quitting.</p> <pre><code>- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender </code></pre> <p>I get an error "Could not merge changes." Which is somewhat expected since there are still operations being performed through the different managedObjectContext. I am then presented with the NSAlert from the template that is generated with a core data application. </p> <p>In the <a href="http://developer.apple.com/library/mac/#DOCUMENTATION/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html" rel="nofollow noreferrer">Threading Programming Guide</a> there is a section called "Be Aware of Thread Behaviors at Quit Time" which alludes to using <a href="http://developer.apple.com/library/mac/#DOCUMENTATION/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/NSApplication/replyToApplicationShouldTerminate:" rel="nofollow noreferrer">replyToApplicationShouldTerminate:</a> method. I'm having a little trouble implementing this. </p> <p><strong>What I would like</strong> is for my application to complete processing the queued items and then terminate without presenting an error message to the user. It would also be helpful to update the view or use a sheet to let the user know that the app is performing some action and will terminate when the action is complete.</p> <p>Where and how would I implement this behavior?</p> <p><strong>Solution</strong>: So I had a few different issues here.</p> <ol> <li><p>I had blocks that were accessing core data in a <code>dispatch_queue</code> preventing my application from terminating gracefully.</p></li> <li><p>When I tried to add a new item to the dispatch_queue a new instance of the dispatch_queue was started on a new thread.</p></li> </ol> <p>What I did to solve this was use <code>NSNotificationCenter</code> in my <code>AppDelegate</code> (where <code>(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender</code> was being called. In the template code that Core Data generates add the following:</p> <pre><code>// Customize this code block to include application-specific recovery steps. if (error) { // Do something here to add queue item in AppController [[NSNotificationCenter defaultCenter] postNotificationName:@"TerminateApplicationFromQueue" object:self]; return NSTerminateLater; } </code></pre> <p>Then in <code>AppController</code> add an observer for the notification (I added this to <code>awakeFromNib</code>):</p> <pre><code>- (void)awakeFromNib { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(terminateApplicationFromQueue:) name:@"TerminateApplicationFromQueue" object:nil]; // Set initial state of struct that dispatch_queue checks to see if it should terminate the application. appTerminating.isAppTerminating = NO; appTerminating.isTerminatingNow = NO; } </code></pre> <p>I have also created a <code>struct</code> that can be checked against to see if the user wants to terminate the application. (I set the initial state of the struct in <code>awakeFromNib</code> above). Place the <code>struct</code> after your <code>@synthesize</code> statements:</p> <pre><code>struct { bool isAppTerminating; bool isTerminatingNow; } appTerminating; </code></pre> <p>Now for the long-running <code>dispatch_queue</code> that is preventing the app from gracefully terminating. When I initially create this <code>dispatch_queue</code>, a for loop is used to add the items that need updating. After this for loop is executed, I have tacked on another queue item that will check the <code>struct</code> to see if the app should terminate:</p> <pre><code>// Additional queue item block to check if app should terminate and then update struct to terminate if required. dispatch_group_async(refreshGroup, trackingQueue, ^{ NSLog(@"check if app should terminate"); if (appTerminating.isAppTerminating) { NSLog(@"app is terminating"); appTerminating.isTerminatingNow = YES; } }); dispatch_release(refreshGroup); </code></pre> <p>And the method to be called when the notification is received:</p> <pre><code>- (void)terminateApplicationFromQueue:(NSNotification *)notification { // Struct to check against at end of dispatch_queue to see if it should shutdown. if (!appTerminating.isAppTerminating) { appTerminating.isAppTerminating = YES; dispatch_queue_t terminateQueue = dispatch_queue_create("com.example.appname.terminate", DISPATCH_QUEUE_SERIAL); // or NULL dispatch_group_t terminateGroup = dispatch_group_create(); dispatch_group_async(terminateGroup, terminateQueue, ^{ NSLog(@"termination queued until after operation is complete"); while (!appTerminating.isTerminatingNow) { // add a little delay before checking termination status again [NSThread sleepForTimeInterval:0.5]; } NSLog(@"terminate now"); [NSApp replyToApplicationShouldTerminate:YES]; }); dispatch_release(terminateGroup); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload