2012-11-22 51 views
1

我的應用程序正在使用的網絡連接在這裏:處理網絡連接的正確方法是什麼?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ 
    . 
    . 
    . 
    receivedData = [[NSMutableData alloc] init]; 
} 

-(void) dataFromWeb{ 
request = [[NSURLRequest alloc] initWithURL: url]; 
theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

if (theConnection) { 
    receivedData = [[NSMutableData data] retain]; 
    NSLog(@"** NSURL request sent !"); 
} else { 

    NSLog(@"Connection failed"); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    . 
    . 
    . 
    [theConnection release]; 
    [request release]; 

// Here - using receivedData 
[receivedData release]; 
} 

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

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

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

。相傳在應用程序的道路是這樣的片段(onButtonPressed):

if (theConnection) { 
    // Create the NSMutableData to hold the received data. 
    // receivedData is an instance variable declared elsewhere. 
    receivedData = [[NSMutableData data] retain]; 
} else { 
    NSLog(@"Connection failed"); 
} 

我想了解的是:

  • 如果我想創造另一個同步的URLRequest,我需要使用不同的連接,以便從網絡到達的數據在檢索時不會混淆。

  • 在這段代碼中,會發生什麼情況是,有時代碼會崩潰的功能didReceiveResponse()setLength:0線,當應用程序崩潰,我看到receivedData=nil我應該改變行

    if(receivedData!=nil) 
        [receivedData setLength:0]; 
    else 
        receivedData = [[NSMutableData data] retain]; 
    
  • 我不太確定這行是幹什麼的receivedData = [[NSMutableData data] retain];

回答

1

我認爲要處理2個連接的最簡單方法是複製NSMutableData。我以這種方式使用,它對我來說非常合適。

receivedData2 = [[NSMutableData alloc] init]; 

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

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

然後,在方法,你問receivedData2或receivedData

而當你使用它不要忘了:你希望第二個連接

拳你做這點這樣做:

receivedData2=nil; 
[receivedData2 setLength:0]; 
0
  1. 你當然會需要不同的NSURLConnection
  2. 你可以做到這一點,但更好地發現,爲什麼它是零,因爲它不應該。
  3. 它分配一個空的NSMutableData對象。但是這對我來說看起來很難看,因爲你創建了一個自動釋放的對象並保留它。最好寫下[NSMutableData new][[NSMutableData alloc] init]
相關問題