NSOperationQueue waitUntilAllOperationsAreFinished vs. performSelectorOnMainThread
I have background NSInvocationOperation creating and saving NSArray to the NSManagedObject subclass.
I know that save should happen on main thread, so I use performSelectorOnMainThread for save in the operation.
When user pushes home button on iPhone 3G, app is going to quit. In applicationDidEnterBackground I do [queue waitUntilAllOperationsAreFinished], so that NSInvocationOperation has time to finish.
The problem is, that it waits only for "background part" of the operation - app is shutted down before performSelectorOnMainThread part of the operation is call开发者_运维技巧ed. This means my NSManagedObject is not saved.
I tried to save object in operation's thread - app is shutted gracefully and changes are saved. But I think this is not good as NSManagedObject is not thread safe. Or is it OK to do this?
It seems like catch 22. I must be missing something - is there any elegant way how to solve this?
You should just do the save operation in the background using a separate context that notifies the main context. This means creating, fetching, and saving managed objects should be done on this separate context and this is documented in the Core Data - Concurrency with Core Data. You should also start a background task to ensure you have enough time to finish saving the data.
精彩评论