开发者

Core Data and Concurrency, 2 solution, which way shou I use?

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];
}

- (开发者_JAVA百科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.


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."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜