2010-06-23 41 views
1

爲什麼我們在xml解析中使用NSURLConnection對象,即。在調用xml web服務時使用NSURLConnection的目的..?

爲如:

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

and then NSURLConnection delegate methods invoked 
like: 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 
    [connection release]; 
    [receivedData release]; 

} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 
    [receivedData setLength:0]; 

} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    [receivedData appendData:data]; 

} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ 

    if(ObjNSXMLParser!=nil && [ObjNSXMLParser retainCount]>0){ 
     [ObjNSXMLParser release]; 
     ObjNSXMLParser = nil; 
    } 

    ObjNSXMLParser = [[NSXMLParser alloc]initWithData:receivedData]; 
    ObjNSXMLParser.delegate=self; 
    [ObjNSXMLParser parse]; 

} 

=============================== 但是我們也有數據直接通過:無需初始化NSURLConnection的對象:

NSData *dt = [NSData DatawithcontentsofURL:urlname]; 

哪種方法是最好的,爲什麼?

回答

1

[NSDATA dataWithContentsOfURL:urlname]將在獲取數據時阻止您的應用程序。

NSURL將讓你在後臺獲取數據,所以你的UI仍然可以工作。

如果你不介意阻塞你的線程,dataWithContentsOfURL更容易使用。然而,如果你在主線程中這樣做,如果加載需要很長時間,你將會非常煩惱用戶。他們會認爲該應用程序已損壞!