开发者

What is the best way to parse an XML in background using NSTimer

I need to a开发者_如何学编程synchronously parse an XML in a regular interval so that when the user reloads the UITableView using "PullToReload" it loads the updated values. My bet is using NSTimer...

I already have an XML Parser using TBXML:

- (void) xmlParserWrapper
{
...
TBXMLParser *xmlParser = [[TBXMLParser alloc] initWithContext:context];
[xmlParser performSelectorInBackground:@selector(parseXMLFileAtURL:) withObject:xmlUrl];
}

So I tried using NSTimer

{
...
[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(xmlParserWrapper) userInfo:nil repeats:YES];
}

This works fine as long as the user won't touch the GUI while parsing. But when the user clicks on the UITableViewCell, it needs to push a new UITableView to the UINavigationController and fetches the data based on the selected cell value; since the NSManagedContext is empty during the parsing (until it's populated) the application crashed due to 'Invalid predicate: nil RHS'.

My code grows very big now so I can't really paste it here but please let me know which part of the codes you need to see and I'll put it here.

Basically, I just need to have a XML parsing in the background in a regular interval that won't crash the application. I also need it to be in another thread so it won't block the MainThread as the user navigates to the UI.

Thanks in advance, dfox


I am no iOS expert, however this issue is common with any GUI framework, and it is generally solved by using a background, or worker, thread to perform time-consuming tasks leaving the main GUI thread to handle user interaction.

Your solution should be as follows:

  1. Create the worker thread when the application starts.
  2. Use a container (list) class to contain the 'work queue' onto which you will post work for the worker thread. You will need to implement your own class or struct to describe each work unit to perform.
  3. Use a synchronization mechanism to control access to the work queue from both threads.
  4. Implement as much work as possible in the worker thread (i.e. get it to retrieve as well as parse the XML). I would have thought network access is the most time-consuming task here.
  5. Get the worker thread to update the UI elements with new content. There is a synchronization issue to solve here as well.
  6. Terminate the worker thread when the application terminates.

See this Apple Documentation on threads, for an introduction on implementing this under iOS.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜