我在从iOS上的http客户端获取数据时遇到了问题。这是我的client类的代码
@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显示下载了一些字节的数据)。问题是,我的应用程序在还没有从服务器上下载数据的时候就试图检索数据(有200ms的差异),有没有办法让主线程一直等到connectionDidFinishLoading被调用?
发布于 2012-08-02 20:04:46
您在此处分配的NSMutableData:
if (connect) {
receivedData =[NSMutableData data];
}
else {
}可能是自动释放的,因为您正在使用一个返回自动释放对象的方法。
你可以这样做:
self.receivedData = [NSMutableData data]; 如果receivedData是strong/retain属性或
receivedData = [[NSMutableData alloc] init]; //但是您需要了解内存管理规则,以确保您不会在这里泄漏内存。
https://stackoverflow.com/questions/11776613
复制相似问题