NSURLConnection在发布NSMutableData时崩溃

时间:2012-05-13 07:31:09

标签: ios xcode crash nsurlconnection nsmutabledata

我已按照Using 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];
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您的代码正在执行异步调用。每次调用start方法时,都会创建NSURLConnection对象的新实例,但是只有一个对象(getData)用于数据。考虑一些如何同时进行两次调用,当第一次失败时它释放你的连接和getData对象,当第二次失败时它会成功释放你的连接对象但你的getData对象在之前的失败调用中已经释放,导致代码崩溃。 / p>

要解决此问题,请在释放后将对象设置为nil,并在必要时执行nil检查。

答案 1 :(得分:0)

您需要发布getData而不是myNSMutableData