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 applicationWi开发者_Go百科llTerminate:
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
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.)
Not sure here, but does NSManagedObjectContext retain its store coordinator and object model? In that case, wouldn't it suffice to have your controller retain the managed object context?
精彩评论