0

I'm having problem with getting data from my http client on iOS. This is my code for client class

@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]);



}

but when i'm trying to get data from this client:

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

data variable is empty, but data was received (NSLog showed the fact of downloading some bytes of data). The problem is that my app is trying retrieve data when it still hasn't been downloaded from server (there is 200 ms difference) is there any way to make main thread to wait until connectionDidFinishLoading is called?

4

1 回答 1

0

您在此处分配的 NSMutableData:

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

}
else {

}

可能正在自动释放,因为您使用的是返回自动释放对象的方法。

您应该执行以下操作:

self.receivedData = [NSMutableData data]; 

如果接收数据是强/保留属性或

receivedData = [[NSMutableData alloc] init]; 

// 但你需要了解内存管理规则,以确保你没有在这里泄漏内存。

于 2012-08-02T12:04:46.107 回答