该应用程序提取 XML提要,解析出来并显示表示 XML提要中项目的列表.单击列表中的项目时,应用程序将使用先前提取的XML提要中的一个属性提取新的XML提要.这发生了几层拉,解析,显示和用户选择再次做同样的事情.现在大多数XML元素结构都是这样的:
(这些只是为了演示正在发生的事情的简单示例)
> http://site.com/get/items/
返回(显示新视图的信息):
<items> <item id="123" name="item 1" /> <item id="124" name="item 2" /> <item id="125" name="item 3" /> </itmes>
> http://site.com/get/description/123(示例用户已选择项目1,拨打电话获取说明)
收益:
<itemDescription> <description itemId="123" name="desc 1" description="blah 1" /> </itemDescription>
想知道:
>我应该在每个视图中都有连接类/对象或新连接吗?
>我应该在每个视图中都有解析器类/对象或解析XML提要吗?
>我还希望存储一些返回的数据,因此如果用户导航回主项列表,我不需要再次调用XML提要,但我每次都需要解析itemsDescription XML提要.
我已经看了几个解析XML的教程,我得到了如何做到这一点的要点,希望更多地关注设计和可重用性,而不是在每个新视图中复制代码.或者我是如何做到这一点的
解决方法
Basic structure(没有离线模式):
The SeismicXML sample application demonstrates how to use NSXMLParser
to parse XML data. When you launch the application it downloads and
parses an RSS Feed from the United States Geological Survey (USGS)
that provides data on recent earthquakes around the world. It displays
the location,date,and magnitude of each earthquake,along with a
color-coded graphic that indicates the severity of the earthquake. The
XML parsing occurs on a background thread using NSOperation and
updates the earthquakes table view with batches of parsed objects.
Advanced structure(有离线模式):
Demonstrates how to use Core Data in a multi-threaded environment,
following the first recommended pattern mentioned in the Core Data
Programming Guide.Based on the SeismicXML sample,it downloads and parses an RSS Feed
from the United States Geological Survey (USGS) that provides data on
recent earthquakes around the world. What makes this sample different
is that it persistently stores earthquakes using Core Data. Each time
you launch the app,it downloads new earthquake data,parses it in an
NSOperation which checks for duplicates and stores newly founded
earthquakes as managed objects.For those new to Core Data,it can be helpful to compare SeismicXML
sample with this sample and notice the necessary ingredients to
introduce Core Data in your application.
关于cwieland的回答我不会使用ASIHTTPRequest,因为它是outdated,所以如果你想按照他的方法我会建议你使用AFNetworking,你可以轻松快速地处理XML请求:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]]; AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request,NSHTTPURLResponse *response,NSXMLParser *XMLParser) { XMLParser.delegate = self; [XMLParser parse]; } failure:nil]; NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; [queue addOperation:operation];