iOS:如何解析 XML 进行实时搜索 [英] iOS: How to parse XML for real-time search

查看:54
本文介绍了iOS:如何解析 XML 进行实时搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在解析一个 XML 文件,如 Apple (LazyTableImages) 的示例.一切正常.我想添加一个实时搜索 (UISearch),它必须解析另一个 XML 文件(专门为搜索而编程).如何在不冻结屏幕的情况下解析此文件?

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?

推荐答案

您使用 GCD 并分派一个块来执行此操作,同时在后台进行解析(并且可能显示一个微调器).您的 XML 解析器委托应该查看取消"标志,因此如果用户执行诸如点击取消或后退按钮之类的操作,您会立即取消 xml 解析并允许当前操作停止.

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.

因此您将有一个 ivar 来保存 NSXMLParser,以及您的类中的一个在解析完成时调用的方法:

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

如果用户输入cancel(假设XML对象很大,解析需要很多秒),那么你可以在action方法中简单的发送

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

这篇关于iOS:如何解析 XML 进行实时搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆