首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS httprequest数据恢复

iOS httprequest数据恢复
EN

Stack Overflow用户
提问于 2012-08-02 19:37:36
回答 1查看 128关注 0票数 0

我在从iOS上的http客户端获取数据时遇到了问题。这是我的client类的代码

代码语言:javascript
复制
@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]);



}

但是当我试图从这个客户端获取数据时:

代码语言:javascript
复制
NSURL *url = [NSURL URLWithString:@"http://ya.ru"];
MAHTTPClient *client = [MAHTTPClient alloc];
[client HTTPRequest1:url];
 NSMutableData *data = client.receivedData;

数据变量为空,但收到了数据(NSLog显示下载了一些字节的数据)。问题是,我的应用程序在还没有从服务器上下载数据的时候就试图检索数据(有200ms的差异),有没有办法让主线程一直等到connectionDidFinishLoading被调用?

EN

回答 1

Stack Overflow用户

发布于 2012-08-02 20:04:46

您在此处分配的NSMutableData:

代码语言:javascript
复制
if (connect) {
    receivedData =[NSMutableData data];

}
else {

}

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

你可以这样做:

代码语言:javascript
复制
self.receivedData = [NSMutableData data]; 

如果receivedData是strong/retain属性或

代码语言:javascript
复制
receivedData = [[NSMutableData alloc] init]; 

//但是您需要了解内存管理规则,以确保您不会在这里泄漏内存。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11776613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档