在释放NSMutableData NSURLConnection的崩溃(NSURLConnectio

2019-10-16 16:45发布

我从依照指示使用NSURLConnection的在方法,有时(非常非常难得)我的项目崩溃。

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
    [myNSMutableData release];
}

它死机当我尝试释放我NSMutableData 。 我想知道为什么它崩溃!

一些代码,我使用:

- (void) start
{
    while (1)
    {
        NSString *stringURL = @"http://www.iwheelbuy.com/get.php?sex=1";
        NSURL *url = [NSURL URLWithString:stringURL];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        if (connection)
        {
            getData = [[NSMutableData data] retain];
            break;
        }
        else
        {
            NSLog(@"no start connection");
        }
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([connection.originalRequest.URL.absoluteString rangeOfString:@"get.php"].location != NSNotFound)
    {
        [getData setLength:0];
    }
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if ([connection.originalRequest.URL.absoluteString rangeOfString:@"get.php"].location != NSNotFound)
    {
        [connection release];
        [getData release];
    }
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    if ([connection.originalRequest.URL.absoluteString rangeOfString:@"get.php"].location != NSNotFound)
    {
        [connection release];
        NSString *html = [[NSString alloc] initWithData:getData encoding:NSASCIIStringEncoding];
        [getData release];
        if ([html rangeOfString:@"id1="].location != NSNotFound && [html rangeOfString:@"id2="].location != NSNotFound)
        {
            NSLog(@"everything is OKAY");
            [html release];
        }
        else
        {
            [html release];
            [self start];
        }
    }
}

Answer 1:

您的代码正在执行异步调用。 每次你打电话给start方法一次创建NSURLConnection的对象的新实例,但你必须对数据对象只有一个(的getData)。 考虑到一些如何有两个同时呼叫,当第一次失败了它松开的连接和对象的getData,当第二个失败了,它成功地释放连接对象,但你的getData对象已经发布的前一失败调用导致你的代码崩溃。

为了解决这个问题总是设置你的对象为nil你释放后他们并执行零检查必要。



Answer 2:

你需要释放getData而不是myNSMutableData



文章来源: NSURLConnection crash on releasing NSMutableData