2012-08-02 33 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