当我使用ASIHTTPRequest取消异步Web请求时获得EXC_BAD_ACCESS

owe*_*wen 2 iphone objective-c asihttprequest

我在iPhone模拟器中运行下面的示例代码没有问题,但是当我在iPhone中运行它时,当我调用[asiRequest cancel]时,我总是得到一个EXC_BAD_ACCESS.谁有人可以帮忙?谢谢.

ASIHTTPRequest *asiRequest;

-(IBAction)request1{
    NSLog(@"request starting");
    [self sendRequest];
}
-(IBAction)cancel1{
    NSLog(@"request caceling");
    if(asiRequest)
        [asiRequest cancel];

}

-(void)sendRequest{
    asiRequest=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://maps.google.com/"]];
    [asiRequest setDelegate:self];
    [asiRequest startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"requestFinished");
    asiRequest=nil;
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"request Error=%@",[request error]);
    asiRequest=nil;
}
Run Code Online (Sandbox Code Playgroud)

检查api后,我想我不应该在requestFinished或requestFailed中释放它

我怎么能在完成后发布它?

- (void)cancel
{
    #if DEBUG_REQUEST_STATUS
    NSLog(@"Request cancelled: %@",self);
    #endif
    [[self cancelledLock] lock];

    if ([self isCancelled] || [self complete]) {
        [[self cancelledLock] unlock];
        return;
    }

    [self failWithError:ASIRequestCancelledError];
    [self setComplete:YES];
    [self cancelLoad];
    [[self cancelledLock] unlock];

    // Must tell the operation to cancel after we unlock, as this request might be dealloced and then NSLock will log an error
    [super cancel];
}
Run Code Online (Sandbox Code Playgroud)

Gra*_*aul 9

您需要保留ASIHTTPRequest.因为请求是通过使用便利构造函数自动释放的,所以必须保留它以使其保持通过当前运行循环的结束.

另外,请注意,您并不需要检查,如果asiRequest不是nilcancel1::将消息发送到零什么也不做,并且没有不良影响.