开发者

Parse XML into CoreData on Background Thread to not lock up UI

开发者 https://www.devze.com 2023-03-06 12:26 出处:网络
My application parses an xml file into coredata to populate a uitableview. When I trigger a refresh it should go and download a new xml file, parse it on a background thread, and then save it all at o

My application parses an xml file into coredata to populate a uitableview. When I trigger a refresh it should go and download a new xml file, parse it on a background thread, and then save it all at once to the managedobjectcontext (replacing the old managedobjectcontext data) and then update the table. This way, similar to Twitter App, 开发者_运维问答the user can trigger a reload and still scroll around while it's loading.

This seems like a pretty standard thing to do, but I can't seem to find any help on it out there.

Currently I am downloading the XML in my App Delegate using NSURLConnection to not lock up the UI. Once it is finished downloading it calls:

ParseOperation *parseOperation = [[ParseOperation alloc] initWithData:receivedData andArray:[NSManagedObjectContext defaultContext]];

[self.parseQueue addOperation:parseOperation];

This starts the parse in what I believe is a background thread. I can here download the xml and then....

2 Problems: 1) How do I save it to the main thread's managedobjectcontext? 2) How can I access old entities in core data to compare to the updated xml coming in?

Surely someone has to have run into this before... any sample code out there?


It sounds like you have the right general idea but your execution may be off.

First, just putting a Core Data related operation into an NSOperation doesn't make it all magically work. You need to be sure to dedicate a MOC to the operation instance (don't use the main thread MOC) and then either use the performBlock method to ensure the right queue is used OR have a dedicated MOC attached to the same PSC and use the 'did save' notifications to merge changes back to the main thread MOC.

As for the second part of your question, you'll need to perform a fetch of the existing data to determine if items are new or updates and then react accordingly. Instead of fetching for each new item you might want to fetch up front and then use in-memory predicates to filter the data you're looking for from that set (this approach is faster but could cause memory pressure depending on the number of items and how large they are in memory when faulted in).

0

精彩评论

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