1

I have followed the instruction from Using NSURLConnection and sometimes (very very seldom) my project crashes in method.

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

It crashes when i try to release my NSMutableData. I want to know why it crashes!

Some code I use:

- (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];
        }
    }
}
4

2 回答 2

1

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

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

于 2012-05-13T09:01:39.367 回答
0

You need to release getData instead of myNSMutableData.

于 2012-05-13T07:34:50.560 回答