Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Will Terminate Notification & Saving Drafts (Core Data)

If the user is currently in my edit view controller, I want to be able to save the changes when the user closes my app. To do this I am observing the UIApplicationWillTerminateNotification of the shared application. In my app delegate, I use the applicationWillTerminate: method to close things down and release all my core data contexts.

The problem I'm finding is that the applicationWillTerminate: method in the app delegate gets called before any observers react to the UIApplicationWillTerminateNotification notification. This means that my core data stack has been released and closed before my edit view controller gets a chance to save anything!

How is this usually overcome because I can't see a way!

Many thanks,

Michael

like image 256
Michael Waterfall Avatar asked Nov 16 '09 20:11

Michael Waterfall


1 Answers

Edit: The first (notification-based) approach probably won't work due to the inner workings of run loops and notifications.

If you want to stick with the notification-based architecture, you can actually post your own notifications from within applicationWillTerminate:. Simply create your own MyApplicationWillTerminate notification, then call postNotification: on [NSNotificationCenter defaultCenter]. Then have your edit controller register for instances of MyApplicationWillTerminate rather than the default UIApplicationWillTerminateNotification.

Another choice is to have your app delegate store an instance of your edit controller if it's visible, then in applicationWillTerminate: save the new info before releasing the Core Data context. This pollutes your app delegate with extra instance variables, though, so it may not be the optimal solution.

A last thought: why not have the app save whatever edits are being made as the user makes them? That way, you don't have to worry about the app closing halfway through editing a piece of info - the edits are already saved, and you can simply release the Core Data stuff as you already are. (This may not be appropriate for you; I really couldn't say without knowing more about your app structure and what data you're editing.)

like image 53
Tim Avatar answered Oct 14 '22 17:10

Tim