iTunes XML解析可可 [英] iTunes XML Parsing in cocoa

查看:151
本文介绍了iTunes XML解析可可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个可可的应用程序。我需要解析大型(约25Mb)的iTunes XML文件。我现在使用以下代码片段
NSDictionary * itunesDatabase = [NSDictionary dictionaryWithContentsOfFile:itunesPath];
但是这有点慢
有更快的方法将整个数据加载到字典中

I am developing an application in cocoa .I need to parse a iTunes XML file of large size(about 25Mb).I am using the following code snippet now NSDictionary *itunesDatabase = [NSDictionary dictionaryWithContentsOfFile:itunesPath]; But this is a little bit slow Is there any faster method to load the entire data to a dictionary??

推荐答案

因为 NSDictionary 会将所有内容一次读入内存。对于大型iTunes库,这可能需要很长时间,并且随意使用活动监视器来确认这一点 - 一个指标内存负载。 (这是该内存量的精确技术术语)

The reason you're having such slow performance is because NSDictionary reads everything into memory all at once. For a large iTunes library, this can take a long time and -- feel free to confirm this with Activity Monitor -- a metric assload of memory. (This is the precise technical term for that amount of memory)

这些情况下的替代方法是使用基于回调的XML解析器(通常称为SAX解析器)。这些解析XML文档的实体一次,并调用您的回调方法。在Cocoa中, NSXMLParser 类提供此功能。您将类设置为其委托,调用 parse 方法,并且解析器启动调用委托方法,因为它读取XML文件中的标签,属性,文本等。

The alternative in these situations is to use a callback-based XML parser (generally known as "SAX" parsers). These parse XML documents an entity at a time and call your callback methods. In Cocoa, the NSXMLParser class provides this functionality. You set your class as its delegate, call the parse method, and the parser starts calls the delegate methods as it reads tags, attributes, text, etc. in the XML file.

现在,这显然比将所有内容都加载到 NSDictionary 更难,您需要自己跟踪状态信息。而且你必须逐步建立你的对象,所以组织你的类可能很困难。

Now, this is obviously harder than just loading everything into an NSDictionary and walking the resulting tree of objects. You'll need to keep track of state information yourself. And you'll have to "build up" your objects progressively, so organizing your classes can be difficult.

但是,你可以忽略你不感兴趣的XML ,并且节省了大量的内存。而且,根据您从iTunes中获取的数据,您还可以在获得所需的数据后立即结束解析。即使这最终需要相当长一段时间,至少你可以显示你的用户的进度条或一些其他迹象表明你的程序是工作,这比停止10-20秒更好,而 NSDictionary 加载一个巨大的XML文件。

However, you can ignore the XML you aren't interested in, and that saves a lot of memory. And, depending on what data you're getting out of iTunes, you may also be able to end the parsing as soon as you've gotten the data you need. Even if this does end up taking quite a while, at least you'll be able to show your user a progress bar or some other indication that your program is working, which is much better than just hanging for 10-20 seconds while NSDictionary loads a giant XML file.

这篇关于iTunes XML解析可可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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