我在iOS上从我的http客户端获取数据时遇到问题。这是我的客户端类代码
@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 :(得分:0)
您在此处分配的NSMutableData:
if (connect) {
receivedData =[NSMutableData data];
}
else {
}
可能正在自动释放,因为您正在使用返回自动释放对象的方法。
您应该执行以下操作:
self.receivedData = [NSMutableData data];
如果receivedData是强/保留属性或
receivedData = [[NSMutableData alloc] init];
//但你需要了解内存管理规则,以确保你没有泄漏内存。