2012-08-02 34 views
0

我在從iOS上的http客戶端獲取數據時遇到問題。這是我的客戶端類代碼iOS httprequest數據恢復

@synthesize receivedData; 

- (void) HTTPRequest1 :(NSURL *) url { 
     NSURLRequest *req = [NSURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

    NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:req delegate:self]; 


    if (connect) { 
     receivedData =[NSMutableData data]; 

    } 
    else { 

    } 


} 

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


} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 

     [self.receivedData appendData:data]; 
    //receivedData 

} 

- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error 
{ 

    NSLog(@"Connection failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 

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

    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); 



} 

但是當我試圖從該客戶端得到數據:

NSURL *url = [NSURL URLWithString:@"http://ya.ru"]; 
MAHTTPClient *client = [MAHTTPClient alloc]; 
[client HTTPRequest1:url]; 
NSMutableData *data = client.receivedData; 

數據變量爲空,但接收到的數據(的NSLog顯示下載的事實一些數據字節)。問題是,我的應用程序嘗試檢索數據時,仍然沒有從服務器下載(有200毫秒的差異)有什麼辦法讓主線程等待,直到connectionDidFinishLoading被調用?

回答

0

,你在這裏分配的NSMutableData:

if (connect) { 
    receivedData =[NSMutableData data]; 

} 
else { 

} 

可能正在自動釋放,因爲你使用的是返回一個自動釋放對象的方法。

您應該這樣做:

self.receivedData = [NSMutableData data]; 

中頻receivedData是強/保留屬性或

receivedData = [[NSMutableData alloc] init]; 

//但你需要了解的內存管理規則,以確保你在這裏沒有泄漏記憶。

+0

仍然無法工作,我無法從我的客戶端檢索數據,但是當我嘗試訪問connectionDidFinishLoading方法中的數據時,receivedData包含從服務器接收的所有內容,但仍然從我的視圖控制器訪問接收到的數據時,它是空的 – Chaosit 2012-08-02 12:10:18