今のところ、Apple の例 (LazyTableImages) のような XML ファイルを解析しています。すべて正常に動作します。別の XML ファイル (検索用に特別にプログラムされたもの) を解析する必要があるリアルタイム検索 (UISearch) を追加したいと思います。画面をフリーズせずにこのファイルを解析するにはどうすればよいですか?
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];