For now I am parsing a XML file like the example from Apple (LazyTableImages). Everything works fine. I'd like to add a real-time search (UISearch) which has to parse another XML file (specially programmed for the search). How can I parse this file without freezing the screen?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You use a GCD and dispatch a block to do this while parsing in the background (and maybe showing a spinner). Your XML parser delegate should be looking at a "cancel" flag, so if the user does something like hit cancel or the back button, you cancel the xml parsing immediately and allow the current operation to stop.
EDIT: So you will have an ivar to hold the NSXMLParser, and a method in your class that is called when the parsing is complete:
NSXMLParser *parser;
NSString *searchTerm;
id results; // some mutable collection that the parser stores things into
- (void)parseFinished:(id)result; // result can be an array or dictionary, whatever you want
when the user has entered some text and you want to search:
searchTerm = ....; // set it
parser = [NSXMLParser alloc] init....];
parsedItems = ....
dispatch_async(dispatch_get_global_queue(0,0), ^
{
BOOL ret = [parser parse];
id myResultObject;
if(ret == YES) {
// your delegate methods have populated parsedItems now
search through them using searchTerm
create and fill in myresultObject, some collection/string/number whatever
}
// nil myResultObject means that parser failed
dispatch_async(dispatch_get_main_queue(), ^[self parseFinished:myResultObject];} );
} );
If the user types cancel (suppose XML object is huge, and it takes many seconds to parse), then you would in the action method simply send
[parser abortParsing];