I am new to Core Data world and I am using iOS 4 as base framework and using core data to perform the operation against my local SQLight DB, I am designing offline application but at some point when user come online I need to pull some updated data from server and push the same into the local DB, plus at the same time user might be performing some inserts and updated into same DB through UI as well.
So there would be two sets of operations happening on the same DB on same time
1) User would be doing some inserts or updates through UI Views
2) Synchronization engine running in the background might be pulling some data and pushing it into the local DB
In such situation there might be issue with shared managed context being saved [with [context save:&error];], because there is a possibility that context might end up saving the wrong data.
I could think of having two solutions for the same
1) Creating another persistent store pointing to same DB, but doing so could lead to high memory consumption on device
2) Creating different开发者_C百科 thread for synchronization engine, but not sure how to deal with it.
Can you guys please shade some light on this, or am I thinking in completely wrong direction?
Thanks Ajay Sawant
Personally, I would use threads. (Actually, I'd use an NSOperation but that's just a fancy thread).
Never share a managed context between threads.
If you want your transactions to be separate (i.e. background updates etc), use a different managed object context for each one.
You should only use one persistentStoreCoordinator but create a managedObjectContext from it for each thread in your app.
This also means that you can't pass managed objects between threads but it's perfectly to pass objectIDs i.e. if you want to tell the main thread something has been done :
// On your background thread . . .
[managedObjectContext save:nil];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[myThing objectID], @"id", nil];
[NSNotificationCenter defaultCenter] postNotificationName:@"something-happened" object:self userIfno:userInfo];
On the main thread you should use objectWithID method to get a new managed object for the main thread's managedObjectContext.
See this document for more details
精彩评论