`
wsqwsq000
  • 浏览: 673637 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

深度解析Cocoa异步请求和libxml2.dylib教程

 
阅读更多

本文介绍的是深度解析Cocoa异步请求和libxml2.dylib教程,,主要介绍了cocoa异步请求的过程,先来看详细内容

深度解析Cocoa异步请求libxml2.dylib教程是本文要介绍的内容,不多说,直接进入话题,很早就在cocoachina上看到这个框架了,今天终于有机会来使用这个东东了.

我这里写一下,如何往iphone项目中添加这个框架.

步骤如下:

1.下载该framework : http://github.com/pokeb/asi-http-request/tree

2.将class根目录下的文件全拷贝到自己的项目中,另外还要在 External/Reachability/下将其中的Reachability.h/m

也拷贝到自己的项目中.

3.添加需要的framework.可以参考 http://allseeing-i.com/ASIHTTPRequest/Setup-instructions

需要额外添加的有: CFNetwork.framework, MobileCoreServices.framework,SystemConfiguration.framework,libz.1.2.3.dylib,libxml2.dylib

然后运行项目,会发现有很多xml相关的error,不用急,这时因为libxml2.dylib这个framework(这个框架不是很friendly,我们还需要做一些工作).

在xcode中project->edit project settings->然后search "search paths",然后在path中添加 /usr/include/libxml2

这样就ok了,可以根据官方的教程来学习了.

http://allseeing-i.com/ASIHTTPRequest/How-to-use

我下了一个sample code  XMLPerformance 解析xml,我建了一个工程照着上面做,但是编译时提示错误,

  1. error libxml/tree.h: No such file or directory 

我立刻想到没有add Frameworks ,我把libsqlite3.dylib 和 libxml2.dylib都加进去了,但是还是报错。

  1. error libxml/tree.h: No such file or directory  
  2. An error on the .h is a compile-time error with your Header Search Paths, not a .dylib or a linker error.  
  3. You have to ensure that /usr/include/libxml2 is in your Header Search Paths in your Release configuration。 

在iphone开发中,异步操作是一个永恒的话题,尤其当iphone手机需要和远程服务器进行交互时,使用异步请求是很普遍的做法。

通常,这需要NSURLConnection和NSOperation结合起来使用。这方面的资料网络上自然有不少的介绍,不过要找一个能运行的代码也并不容易。许多文章介绍的并不全面,或者使用了过时的SDK,在新IOS版本下并不适用(当前最新的ios是4.2了)。这些代码很经典,但仍然很容易使人误入歧途。

本文总结了众多文档介绍的方法和代码,揭示了异步操作中的实现细节和初学者(包括笔者)易犯的错误,使后来者少走弯路。

一、使用NSOperation实现异步请求

1、新建类,继承自NSOperation。

  1. @interface URLOperation : NSOperation  
  2. {  
  3.     NSURLRequest*  _request;  
  4.     NSURLConnection* _connection;  
  5.     NSMutableData* _data;  
  6.     //构建gb2312的encoding  
  7.     NSStringEncoding enc;  
  8. }  
  9. - (id)initWithURLString:(NSString *)url;  
  10. @property (readonly) NSData *data;  
  11. @end 

接口部分不多做介绍,我们来看实现部分。

首先是带一个NSString参数的构造函数。在其中初始化成员变量。

其中enc是 NSStringEncoding 类型,因为服务器返回的字符中使用了中文,所以我们通过它指定了一个gb2312的字符编码。

许多资料中说,需要在NSOperation中重载一个叫做isConcurrent的函数并在其中返回YES,否则不支持异步执行。但是实际上,我们在这里注释了这个重载方法,程序也没有报任何错误,其执行方式依然是异步的。

  1. @implementation URLOperation  
  2. @synthesize data=_data;  
  3. - (id)initWithURLString:(NSString *)url {  
  4.     if (self = [self init]) {  
  5.         NSLog(@"%@",url);  
  6.         _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url  
  7.         //构建gb2312的encoding  
  8.         enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);  
  9.         _data = [[NSMutableData data] retain];  
  10.     }  
  11.     return self;  
  12. }  
  13. - (void)dealloc {  
  14.     [_request release],_request=nil;  
  15.     [_data release],_data=nil;  
  16.     [_connection release],_connection=nil;  
  17.     [super dealloc];  
  18. }  
  19. // 如果不重载下面的函数,异步方式调用会出错  
  20. //- (BOOL)isConcurrent {  
  21. //  return YES;//返回yes表示支持异步调用,否则为支持同步调用  
  22. //} 

整个类中最重要的方法是start方法。Start是NSOperation类的主方法,主方法的叫法充分说明了其重要性,因为这个方法执行完后,该NSOperation的执行线程就结束了(返回调用者的主线程),同时对象实例就会被释放,也就意味着你定义的其他代码(包括delegate方法)也不会被执行。很多资料中的start方法都只有最简单的一句(包括“易飞扬的博客 “的博文):

  1. [NSURLConnection connectionWithRequest:_request delegate:self]; 

如果这样的话,delegate方法没有执行机会。因为start方法结束后delegate(即self对象)已经被释放了,delegate的方法也就无从执行。

所以在上面的代码中,还有一个while循环,这个while循环的退出条件是http连接终止(即请求结束)。当循环结束,我们的工作也就完成了。

  1. // 开始处理-本类的主方法  
  2. - (void)start {  
  3.     if (![self isCancelled]) {  
  4.         NSLog(@"start operation");  
  5.         // 以异步方式处理事件,并设置代理  
  6.         _connection=[[NSURLConnection connectionWithRequest:_request delegate:self]retain];  
  7.         //下面建立一个循环直到连接终止,使线程不离开主方法,否则connection的delegate方法不会被调用,因为主方法结束对象的生命周期即终止  
  8.         //这个问题参考 http://www.cocoabuilder.com/archive/cocoa/279826-nsurlrequest-and-nsoperationqueue.html  
  9.         while(_connection != nil) {  
  10.             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];     
  11.         }  
  12.     }  

接下来,是NSURLConnection的delegate方法,这部分的代码和大部分资料的介绍是一样的,你可以实现全部的delegate方法,但这里我们只实现其中3个就足够了,其余的方法不用理会。如你所见,你可以在其中添加自己想到的任何代码,包括接收数据,进行字符编码或者做xml解析。

  1. #pragma mark NSURLConnection delegate Method  
  2. // 接收到数据(增量)时  
  3. - (void)connection:(NSURLConnection*)connection  
  4.     didReceiveData:(NSData*)data {  
  5.     NSLog(@"connection:");  
  6.     NSLog(@"%@",[[NSString alloc] initWithData:data encoding:enc]);  
  7.     // 添加数据  
  8.  
  9.     [_data appendData:data];  
  10.  
  11. }  
  12. // HTTP请求结束时  
  13. - (void)connectionDidFinishLoading:(NSURLConnection*)connection {  
  14.     [_connection release],_connection=nil;  
  15.     //NSLog(@"%@",[[NSString alloc] initWithData:_data encoding:enc]);  
  16. }  
  17. -(void)connection: (NSURLConnection *) connection didFailWithError: (NSError *) error{  
  18.     NSLog(@"connection error");  
  19. }  
  20. @end 

到此,虽然代码还没有完成,但我们已经可以运行它了。你可以看到console输出的内容,观察程序的运行状态。

2、调用NSOperation

我们的NSOperation类可以在ViewController中调用,也可以直接放在AppDelegate中进行。

在这里,我是通过点击按钮来触发调用代码的:

  1. -(void)loginClicked{  
  2.     //构造登录请求url  
  3.     NSString* url=@”http://google.com”;  
  4.     _queue = [[NSOperationQueue alloc] init];  
  5.     URLOperation* operation=[[URLOperation alloc ]initWithURLString:url];  
  6.     // 开始处理  
  7.     [_queue addOperation:operation];  
  8.     [operation release];//队列已对其retain,可以进行release;  

_queue是一个 NSOperationQueue 对象,当往其中添加 NSOperation 对象后, NSOperation 线程会被自动执行(不是立即执行,根据调度情况)。

3、KVO编程模型

我们的NSOperation完成了向服务器的请求并将服务器数据下载到成员变量_data中了。现在的问题是,由于这一切是通过异步操作进行的,我们无法取得_data中的数据,因为我们不知道什么时候异步操作完成,以便去访问_data属性(假设我们将_data定义为属性了),取得服务器数据。

我们需要一种机制,当NSOperation完成所有工作之后,通知调用线程。

这里我们想到了KVO编程模型(键-值观察模型)。这是cocoa绑定技术中使用的一种设计模式,它可以使一个对象在属性值发生变化时主动通知另一个对象并触发相应的方法。

首先,我们在NSOperation的子类中添加一个BOOL变量,当这个变量变为YES时,标志异步操作已经完成:

  1. BOOL _isFinished; 

在实现中加入这个变量的访问方法:

  1. - (BOOL)isFinished  
  2. {  
  3.     return _isFinished;  

cocoa的KVO模型中,有两种通知观察者的方式,自动通知和手动通知。顾名思义,自动通知由cocoa在属性值变化时自动通知观察者,而手动通知需要在值变化时调用 willChangeValueForKey:和didChangeValueForKey: 方法通知调用者。为求简便,我们一般使用自动通知。

要使用自动通知,需要在 automaticallyNotifiesObserversForKey方法中明确告诉cocoa,哪些键值要使用自动通知:

  1. //重新实现NSObject类中的automaticallyNotifiesObserversForKey:方法,返回yes表示自动通知。  
  2. + (BOOL):(NSString*)key  
  3. {  
  4.     //当这两个值改变时,使用自动通知已注册过的观察者,观察者需要实现observeValueForKeyPath:ofObject:change:context:方法  
  5.     if ([key isEqualToString:@"isFinished"])  
  6.     {  
  7.         return YES;  
  8.     }  
  9.     return [super automaticallyNotifiesObserversForKey:key];  

然后,在需要改变_isFinished变量的地方,使用

  1. [self setValue:[NSNumber numberWithBool:YES] forKey:@"isFinished"]; 

方法,而不是仅仅使用简单赋值。

我们需要在3个地方改变isFinished值为YES,请求结束时、连接出错误,线程被cancel。请在对应的方法代码中加入上面的语句。

最后,需要在观察者的代码中进行注册。打开ViewController中调用NSOperation子类的地方,加入:

  1.     //kvo注册  
  2.     [operation addObserver:self forKeyPath:@"isFinished"  
  3.                    options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:operation];  
  4. 并实现 observeValueForKeyPath 方法:  
  5. //接收变更通知  
  6. - (void)observeValueForKeyPath:(NSString *)keyPath  
  7.                       ofObject:(id)object  
  8.                        change:(NSDictionary *)change  
  9.                        context:(void *)context  
  10. {  
  11.     if ([keyPath isEqual:@"isFinished"]) {  
  12.         BOOL isFinished=[[change objectForKey:NSKeyValueChangeNewKey] intValue];  
  13.         if (isFinished) {//如果服务器数据接收完毕  
  14.             [indicatorView stopAnimating];  
  15.             URLOperation* ctx=(URLOperation*)context;  
  16.             NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);  
  17.             NSLog(@"%@",[[NSString alloc] initWithData:[ctx data] encoding:enc]);  
  18.             //取消kvo注册  
  19.             [ctx removeObserver:self  
  20.                     forKeyPath:@"isFinished"];  
  21.         }        
  22.     }else{  
  23.         // be sure to call the super implementation  
  24.         // if the superclass implements it  
  25.         [super observeValueForKeyPath:keyPath  
  26.                              ofObject:object  
  27.                                change:change  
  28.                               context:context];  
  29.     }  

运行程序,查看控制台的输出。

4、libxml的sax解析接口

iphone和服务器交互通常使用xml数据交换格式,因此本文中也涉及到了xml文件解析的问题。有许多有名气的xml解析器可供我们选择,如: BXML,TouchXML,KissXML,TinyXML的第三方库和GDataXML。

Xml解析分为两类,一类是DOM解析,一类为SAX解析。前者如GDataXML,解析过程中需要建立文档树,操作XML元素时通过树形结构进行导航。DOM解析的特点是便于程序员理解xml文档树结构,API 的使用简单;缺点是速度较SAX解析慢,且内存开销较大。在某些情况下,比如iphone开发,受制于有限的内存空间(一个应用最多可用10几m的内存), DOM解析无法使用(当然,在模拟器上是没有问题的)。

libxml2的是一个开放源码库,默认情况下iPhone SDK 中已经包括在内。它是一个基于C的API,所以在使用上比cocoa的 NSXML要麻烦许多(一种类似c函数的使用方式),但是该库同时支持DOM和SAX解析,其解析速度较快,而且占用内存小,是最适合使用在iphone上的解析器。从性能上讲,所有知名的解析器中,TBXML最快,但在内存占用上,libxml使用的内存开销是最小的。因此,我们决定使用libxml的sax接口。

首先,我们需要在project中导入framework:libxml2.dylib。

虽然libxml是sdk中自带的,但它的头文件却未放在默认的地方,因此还需要我们设置project的build选项:HEADER_SEARCH_PATHS = /usr/include/libxml2,否则libxml库不可用。

然后,我们就可以在源代码中 #import <libxml/tree.h> 了。

假设我们要实现这样的功能:有一个登录按钮,点击后将用户密码帐号发送http请求到服务器(用上文中介绍的异步请求技术),服务器进行验证后以xml文件方式返回验证结果。我们要用libxml的sax方式将这个xml文件解析出来。

服务器返回的xml文件格式可能如下:

<?xml version="1.0" encoding="GB2312" standalone="no" ?>

<root>

<login_info>

<login_status>true</login_status>

</login_info>

<List>

<system Name=xxx Path=xxx ImageIndex=xxx>

……

</List>

</root>


其中有我们最关心的1个元素:login_status 。

如果login_status返回false,说明登录验证失败,否则,服务器除返回login_status外,还会返回一个list元素,包含了一些用户的数据,这些数据是<system>元素的集合。

整个实现步骤见下。

首先,实现一个超类, 这个超类是一个抽象类,许多方法都只是空的,等待subclass去实现。

其中有3个方法与libxml的sax接口相关,是sax解析过程中的3个重要事件的回调方法,分别是元素的开始标记、元素体(开始标记和结束标记之间的文本)、结束标记。Sax中有许多的事件,但绝大部分时间,我们只需要处理这3个事件。因为很多时候,我们只会对xml文件中的元素属性和内容感兴趣,而通过这3个事件已经足以使我们读取到xml节点的属性和内容。

而成员变量中,_root变量是比较关键的,它以dictionary的形式保存了解析结果,因为任何xml文档的根节点都是root,所以无论什么样子的xml文件,都可以放在这个_root 中。

因此我们为 _root 变量提供了一个访问方法getResult,等xml解析结束,可以通过这个方法访问_root。

  1. #import <Foundation/Foundation.h> 
  2. #import <libxml/tree.h> 
  3. @interface BaseXmlParser : NSObject {  
  4.     NSStringEncoding enc;  
  5.     NSMutableDictionary*    _root;  
  6. }  
  7. // Property  
  8. - (void)startElementLocalName:(const xmlChar*)localname  
  9.                        prefix:(const xmlChar*)prefix  
  10.                           URI:(const xmlChar*)URI  
  11.                 nb_namespaces:(int)nb_namespaces  
  12.                    namespaces:(const xmlChar**)namespaces  
  13.                 nb_attributes:(int)nb_attributes  
  14.                  nb_defaulted:(int)nb_defaultedslo  
  15.                    attributes:(const xmlChar**)attributes;  
  16. - (void)endElementLocalName:(const xmlChar*)localname  
  17.                      prefix:(const xmlChar*)prefix URI:(const xmlChar*)URI;  
  18. - (void)charactersFound:(const xmlChar*)ch  
  19.                     len:(int)len;  
  20. -(NSDictionary*)getResult;  
  21. @end  
  22. #import "BaseXmlParser.h"  
  23. @implementation BaseXmlParser  
  24. // Property  
  25.  
  26. -(id)init{  
  27.     if(self=[super init]){  
  28.         //构建gb2312的encoding  
  29.         enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);  
  30.         _root=[[NSMutableDictionary alloc]init];  
  31.     }  
  32.     return self;  
  33. }  
  34. -(void)dealloc{  
  35.     [_root release],_root=nil;  
  36.     [super dealloc];  
  37. }  
  38.  
  39. #pragma mark -- libxml handler,主要是3个回调方法--  
  40.  
  41. //解析元素开始标记时触发,在这里取元素的属性值  
  42. - (void)startElementLocalName:(const xmlChar*)localname  
  43.                        prefix:(const xmlChar*)prefix  
  44.                           URI:(const xmlChar*)URI  
  45.                 nb_namespaces:(int)nb_namespaces  
  46.                    namespaces:(const xmlChar**)namespaces  
  47.                 nb_attributes:(int)nb_attributes  
  48.                  nb_defaulted:(int)nb_defaultedslo  
  49.                    attributes:(const xmlChar**)attributes  
  50. {    
  51. }  
  52. //解析元素结束标记时触发  
  53. - (void)endElementLocalName:(const xmlChar*)localname  
  54.                      prefix:(const xmlChar*)prefix URI:(const xmlChar*)URI  
  55. {  
  56. }  
  57. //解析元素体时触发  
  58. - (void)charactersFound:(const xmlChar*)ch  
  59.                     len:(int)len  
  60. {  
  61. }  
  62. //返回解析结果  
  63. -(NSDictionary*)getResult{  
  64.     return _root;  
  65. }  
  66. @end 

现在我们需要扩展这个BaseXmlParser,并重载其中的3个sax方法。

该子类除了重载父类的3个方法外,还增加了几个成员变量。其中flag是一个int类型,用于sax解析的缘故,解析过程中需要合适的标志变量,用于标志当前处理到的元素标记。为了简单起见,我们没有为每一个标记都设立一个标志,而是统一使用一个int标志,比如flag为1时,表示正在处理login_status标记,为2时,表示正在处理system标记。

回顾前面的xml文件格式,我们其实只关心两种标记,login_status标记和system标记。Login_status标记没有属性,但它的元素体是我们关心的;而system标记则相反,它并没有元素体,但我们需要它的属性值。

这是一个很好的例子。因为它同时展示了属性的解析和元素体的解析。浏览整个类的代码,我们总结出3个sax事件的使用规律是:

如果要读取元素属性,需要在“元素开始标记读取”事件(即 startElementLocalName 方法)中处理;

如果要读取元素体文本,则在“元素体读取”事件(即 charactersFound方法)中处理;

在“元素标记读取”事件( 即endElementLocalName 方法)中,则进行标志变量的改变/归零。

  1. #import <Foundation/Foundation.h> 
  2.  
  3. #import <libxml/tree.h> 
  4.  
  5. #import "BaseXmlParser.h"  
  6.  
  7. @interface DLTLoginParser : BaseXmlParser {  
  8.  
  9.     int flag;  
  10.  
  11.     NSMutableDictionary*    _currentItem;    
  12.  
  13. }
  14.  
  15. - (void)startElementLocalName:(const xmlChar*)localname  
  16.                        prefix:(const xmlChar*)prefix  
  17.                           URI:(const xmlChar*)URI  
  18.                 nb_namespaces:(int)nb_namespaces  
  19.                    namespaces:(const xmlChar**)namespaces  
  20.                 nb_attributes:(int)nb_attributes  
  21.                 nb_defaulted:(int)nb_defaultedslo   
  22.                    attributes:(const xmlChar**)attributes;  
  23.  
  24. - (void):(const xmlChar*)localname  
  25.  
  26.                      prefix:(const xmlChar*)prefix URI:(const xmlChar*)URI;  
  27.  
  28. - (void)charactersFound:(const xmlChar*)ch  
  29.  
  30.                     len:(int)len;  
  31.  
  32. @end  
  33. #import "DLTLoginParser.h"  
  34. @implementation DLTLoginParser  
  35. -(id)init{  
  36.     if(self=[super init]){  
  37.         NSMutableArray* items=[[NSMutableArray alloc]init];
  38.         [_root setObject:items forKey:@"items"];  
  39.         [items release];//已被_root持有了,可以释放
  40.     }
  41.     return self;  
  42. }  
  43.  
  44. -(void)dealloc{  
  45.     [_currentItem release],_currentItem=nil;  
  46.     [super dealloc];  
  47. }  
  48.  
  49. //--------------------------------------------------------------//  
  50.  
  51. #pragma mark -- libxml handler,主要是3个回调方法--  
  52.  
  53. //--------------------------------------------------------------//  
  54.  
  55. //解析元素开始标记时触发,在这里取元素的属性值  
  56. - (void)startElementLocalName:(const xmlChar*)localname  
  57.                        prefix:(const xmlChar*)prefix  
  58.                           URI:(const xmlChar*)URI  
  59.                 nb_namespaces:(int)nb_namespaces  
  60.                    namespaces:(const xmlChar**)namespaces  
  61.                 nb_attributes:(int)nb_attributes  
  62.                  nb_defaulted:(int)nb_defaultedslo  
  63.                    attributes:(const xmlChar**)attributes  
  64. {  
  65.     // login_status,置标志为1  
  66.     if (strncmp((char*)localname, "login_status", sizeof("login_status")) == 0) {  
  67.         flag=1;  
  68.         return;  
  69.     }  
  70.     // system,置标志为2  
  71.     if (strncmp((char*)localname, "system", sizeof("system")) == 0) {  
  72.         flag=2;  
  73.         _currentItem = [NSMutableDictionary dictionary];  
  74.         //查找属性  
  75.         NSString *key,*val;  
  76.         for (int i=0; i<nb_attributes; i++){  
  77.             key = [NSString stringWithCString:(const char*)attributes[0] encoding:NSUTF8StringEncoding];  
  78.             val = [[NSString alloc] initWithBytes:(const void*)attributes[3] length:(attributes[4] - attributes[3]) 
  79. encoding:NSUTF8StringEncoding];  
  80.             NSLog(@"key=%@,val=%@",key,val);  
  81.             if ([@"Name" isEqualToString:key]) {  
  82.                 [_currentItem setObject:val forKey:@"name"];  
  83.                 break;  
  84.             }  
  85.             // [val release];  
  86.             attributes += 5;//指针移动5个字符串,到下一个属性  
  87.         }  
  88.         [[_root objectForKey:@"items"] addObject:_currentItem];  
  89.         return;  
  90.     }  
  91. }  
  92. //解析元素结束标记时触发  
  93. - (void)endElementLocalName:(const xmlChar*)localname  
  94.                      prefix:(const xmlChar*)prefix URI:(const xmlChar*)URI  
  95. {  
  96.     flag=0;//标志归零  
  97. }  
  98. //解析元素体时触发  
  99. - (void)charactersFound:(const xmlChar*)ch  
  100.                     len:(int)len  
  101. {  
  102.     // 取login_status元素体  
  103.     if (flag==1) {  
  104.         NSString*   string;  
  105.         string = [[NSString alloc] initWithBytes:ch length:len encoding:NSUTF8StringEncoding];  
  106.         [_root setObject:string forKey:@"login_status"];  
  107.         NSLog(@"login_status:%@",string);  
  108.     }  
  109. }  
  110. @end 

接下来,改造我们的异步请求操作类URLOperation。首先在interface中增加

两个变量:

  1. xmlParserCtxtPtr  _parserContext; //Xml解析器指针  
  2. BaseXmlParser* baseParser; //Xml解析器 

其中第1个变量(一个结构体)的声明显得有点奇怪,似乎是跟第2个变量混淆了。这是因为libxml是一个c函数库,其函数调用仍然使用一种面向结构的编程风格。所以我们在后面还会看到一些结构体似的变量。

另外,把_data成员的类型从NSMutableData改变为NSMutableDictionary,并把它配置为属性,因为我们的请求结果应当被xml解析器解析为dictionary了:

  1. @property (nonatomic,retain) NSDictionary *data; 

当然,记住为它提供访问方法:

  1. @synthesize data=_data

然后,更改 initWithURLString 构造方法,为其增加一个名为 xmlParser 的参数

  1. - (id)initWithURLString:(NSString *)url xmlParser:(BaseXmlParser*)parser{  
  2.     if (self = [super init]) {  
  3.         baseParser=[parser retain];  
  4.         NSLog(@"%@",url);  
  5.         _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];//[[NSURLRequest requestWithURL:[NSURL URLWithString:url]]retain];  
  6.         //构建gb2312的encoding  
  7.         enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);  
  8.         _data = [[NSMutableData data] retain];  
  9.     }  
  10.     return self;  

在start方法中,我们可以这样创建一个xml解析器指针:

// 创建XML解析器指针

  1. _parserContext = xmlCreatePushParserCtxt(&_saxHandlerStruct, baseParser, NULL, 0, NULL); 

注意第2个参数就是具体实现了sax解析的xml解析器。这个解析器对象是通过构造函数“注入”的。

而第一个参数是一个结构体指针 xmlSAXHandler 结构体,这个结构体我们定义为静态变量(注意把定义放在@implementation⋯⋯@end之外):

//libxml的xmlSAXHandler结构体定义,凡是要实现的handler函数都写在这里,不准备实现的用null代替。一般而言,我们只实现其中3个就够了

  1. static xmlSAXHandler _saxHandlerStruct = {  
  2.     NULL,             
  3.     NULL,            
  4.     NULL,             
  5.     NULL,             
  6.     NULL,             
  7.     NULL,             
  8.     NULL,             
  9.     NULL,             
  10.     NULL,             
  11.     NULL,             
  12.     NULL,             
  13.     NULL,             
  14.     NULL,             
  15.     NULL,             
  16.     NULL,             
  17.     NULL,             
  18.     NULL,             
  19.     charactersFoundHandler,  
  20.     NULL,             
  21.     NULL,             
  22.     NULL,             
  23.     NULL,             
  24.     NULL,             
  25.     NULL,             
  26.     NULL,             
  27.     NULL,             
  28.     NULL,             
  29.     XML_SAX2_MAGIC,   
  30.     NULL,             
  31.     startElementHandler,     
  32.     endElementHandler,       
  33.     NULL,             
  34. }; 

机构体中填入了我们准备实现的3个方法句柄,因此我们还应当定义这3个方法。由于结构体是静态的,只能访问静态成员,所以这3个方法也是静态的:

  1. //3个静态方法的实现,其实是调用了参数ctx的成员方法, ctx在_parserContext初始化时传入  
  2. static void startElementHandler(  
  3.                                 void* ctx,  
  4.                                 const xmlChar* localname,  
  5.                                 const xmlChar* prefix,  
  6.                                 const xmlChar* URI,  
  7.                                 int nb_namespaces,  
  8.                                 const xmlChar** namespaces,  
  9.                                 int nb_attributes,  
  10.                                 int nb_defaulted,  
  11.                                 const xmlChar** attributes)  
  12. {  
  13.     [(BaseXmlParser*)ctx  
  14.      startElementLocalName:localname  
  15.      prefix:prefix URI:URI  
  16.      nb_namespaces:nb_namespaces  
  17.      namespaces:namespaces  
  18.      nb_attributes:nb_attributes  
  19.      nb_defaulted:nb_defaulted  
  20.      attributes:attributes];  
  21. }  
  22. static void endElementHandler(  
  23.                               void* ctx,  
  24.                               const xmlChar* localname,  
  25.                               const xmlChar* prefix,  
  26.                              const xmlChar* URI)  
  27.  
  28. {  
  29.     [(BaseXmlParser*)ctx  
  30.      endElementLocalName:localname  
  31.      prefix:prefix  
  32.      URI:URI];  
  33. }  
  34. static void charactersFoundHandler(  
  35.                                    void* ctx,  
  36.                                    const xmlChar* ch,  
  37.                                    int len)  
  38. {  
  39.     [(BaseXmlParser*)ctx  
  40.      charactersFound:ch len:len];  

其实这3个静态方法只是调用了超类BaseXmlParser的成员方法,他的具体类型依赖于ctx的注入类型,也就是说,这里的ctx可以是任何BaseXmlParser的子类。 实际使用中,我们应该注入其子类,从而可以根据不同的情况为URLOperation“注入”不同的解析器,实现解析不同的xml文件的目的。

现在,需要把解析器应用到NSURLConnection的委托方法中(这里省略了部分代码,只列出了新增加的部分):

  1. #pragma mark NSURLConnection delegate Method  
  2. // 接收到数据(增量)时  
  3. - (void)connection:(NSURLConnection*)connection  
  4.     didReceiveData:(NSData*)data {  
  5.     // 使用libxml解析器进行xml解析  
  6.     xmlParseChunk(_parserContext, (const char*)[data bytes], [data length], 0);  
  7.          ⋯⋯  
  8. }  
  9. // HTTP请求结束时  
  10. - (void)connectionDidFinishLoading:(NSURLConnection*)connection {  
  11.              if(baseParser!=nil && baseParser!=NULL){  
  12.         [self setData:[[NSDictionary alloc] initWithDictionary:[baseParser getResult]]];  
  13.     }else {  
  14.         NSLog(@"baseparser is nil");  
  15.     }  
  16.     // 添加解析数据(结束),注意最后一个参数termindate  
  17.     xmlParseChunk(_parserContext, NULL, 0, 1);  
  18.     // 释放XML解析器  
  19.     if (_parserContext) {  
  20.         xmlFreeParserCtxt(_parserContext), _parserContext = NULL;  
  21.     }  
  22. ⋯⋯  
  23. }  
  24.  
  25. -(void)connection: (NSURLConnection *) connection didFailWithError: (NSError *) error{  
  26.     // 释放XML解析器  
  27.     if (_parserContext) {  
  28.         xmlFreeParserCtxt(_parserContext), _parserContext = NULL;  
  29.     }  
  30.          ⋯⋯  
  31. }  
  32. @end 

接下来,在“登录”按钮中代码也要做相应的修改,因为URLOperation的构造函数要求传递一个具体的xml解析器对象:

  1. //构造xmlparser  
  2. DLTLoginParser* parser=[[DLTLoginParser alloc]init];  
  3. URLOperation* operation=[[URLOperation alloc ]initWithURLString:url xmlParser:parser];  
  4. [parser release]; 

然后,在接收变更通知方法中打印解析结果:

  1. URLOperation* ctx=(URLOperation*)context;  
  2. NSLog(@"%@",[ctx data]); 

后台打印结果:

  1. {  
  2.     items =     (  
  3.                 {  
  4.             name = "\U4e91\U7535\U4f01\U4fe1\U901a";  
  5.         },  
  6.                 {  
  7.             name = "\U79fb\U52a8\U8c03\U5ea6";  
  8.         },  
  9.                 {  
  10.             name = "\U79fb\U52a8\U62a2\U4fee";  
  11.         }  
  12.     );  
  13.     "login_status" = true;  

小结:深度解析Cocoa异步请求libxml2.dylib教程的内容介绍完了,希望本文对你有所帮助!

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics