成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

深度解析Cocoa異步請求和libxml2.dylib教程

移動開發 iOS
本文介紹的是深度解析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.     }  

運行程序,查看控制臺的輸出。

#p#

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方法)中處理;

#p#

在“元素標記讀取”事件( 即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教程的內容介紹完了,希望本文對你有所幫助!

責任編輯:zhaolei 來源: 互聯網
相關推薦

2011-08-10 18:37:32

CocoaMac OS X

2024-07-31 15:57:41

2024-10-15 10:28:43

2020-01-02 16:30:02

Spring BootJava異步請求

2013-12-09 10:34:12

2020-10-09 08:29:24

POSTGET參數

2011-07-20 10:12:33

XCode Cocoa dylib

2011-05-11 17:48:31

CocoaiOS

2024-05-28 00:00:20

ElasticseaJava開發

2011-07-18 16:51:51

Cocoa 單態 模式

2011-07-26 15:14:24

蘋果 Cocoa 內存

2011-07-26 10:42:00

Cocoa Cocoa2d 游戲

2011-07-07 09:54:01

Cocoa Core Foundation

2011-08-11 15:46:55

CocoaCocoa Touch框架

2011-07-29 16:08:31

Objective-C 內存

2025-05-12 01:33:00

異步函數Promise

2011-07-07 13:51:24

Cocoa 框架

2011-05-11 15:27:58

Windows OOPCocoa MVCCocoa

2021-02-17 09:09:15

異步請求

2011-08-10 19:33:09

Cocoa對象
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: www.精品一区| 国产成人免费网站 | 午夜精品网站 | 亚洲高清三级 | 欧美狠狠操 | 91精品国产91久久久久久吃药 | 欧美日韩亚洲国产 | 久久久女女女女999久久 | 九九热这里 | 午夜手机在线视频 | 精品中文字幕一区二区 | 日日骚视频 | 亚洲色片网站 | 黄色免费网站在线看 | 日本不卡一区二区三区在线观看 | 亚洲欧洲精品一区 | 国产福利网站 | 国产精品一区二区三 | 欧美在线国产精品 | 国产精品久久久久国产a级 欧美日本韩国一区二区 | 成人影 | 1级黄色大片 | 亚洲精视频 | 亚洲一区二区三区免费 | 天天天操操操 | 91精品91久久久 | 亚洲一区二区三区在线播放 | 久久久久精 | 人人干人人超 | 在线亚洲免费视频 | www国产亚洲精品 | 国产成人精品久久 | 性色网站| 色一情一乱一伦一区二区三区 | 粉嫩一区二区三区国产精品 | 亚洲人免费视频 | 亚洲欧美国产视频 | 不卡视频在线 | 日韩中文字幕一区 | 久久久激情 | 久久久精彩视频 |