Reputation: 11
I get some data from server and I need to parse it. Then some of the parse result may need to save using core data.
this is my code now:
- (void)receiveSomeMessage:(NSString *)message
{
[self performSelectorInBackground:@selector(parseMessage:) withObject:message];
}
- (void) parseMessage:(NSString *)message
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSManagedObjectContext *BGMOC = [[NSManagedObjectContext alloc] init];
[BGMOC setPersistentStoreCoordinator:[self.appDelegate persistentStoreCoordinator]];
//parse it
//write to core data
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self selector:@selector(addContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:BGMOC];
NSError *saveError;
if (![BGMOC save:&saveError]) {
//handle the error
}
[dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:BGMOC];
}
- (void)addContextDidSave:(NSNotification*)saveNotification {
// Merging changes causes the fetched results controller to update its results
[self.appDelegate.managedObjectContext mergeChangesFromContextDidSaveNotification:saveNotification];
}
This seems to work.
But Apple's Document says: Saving in a Background Thread is Error-prone.
So i wonder is this work:
-(void) parseMessage:(NSString *)message
{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//parse it and save it to a dictionary
[self performSelectorOnMainThread:@selector(saveToCoreData:) withObject:dictionary waitUntilDone:YES];
[pool release];
}
After parse the message,I packet it into a dictionery and pass it to main thread and do the core data thing there. Does this work? if it works, is it better?
Thanks.
Upvotes: 1
Views: 602
Reputation: 64428
The Apple docs don't say that saving in the background is technologically error-prone, they imply that programmers are prone to make errors when saving in the background:
Asynchronous queues and threads do not prevent an application from quitting. (Specifically, all NSThread-based threads are “detached”—see the documentation for pthread for complete details—and a process runs only until all not-detached threads have exited.) If you perform a save operation in a background thread, therefore, it may be killed before it is able to complete. If you need to save on a background thread, you must write additional code such that the main thread prevents the application from quitting until all the save operation is complete.
Translation: "When quitting, the programmer has to pay specific attention to the save state of background operations and, a lot of the time, they don't."
Upvotes: 3