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

时间:2010-01-25 00:09:22

标签: 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;
}

检查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];
}

2 个答案:

答案 0 :(得分:9)

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

此外,请注意您无需检查asiRequestnil是否cancel1::向nil发送消息不会做任何事情,并且没有任何不利影响。

答案 1 :(得分:1)

我再次更改了我的代码

它现在运行正常,我想我唯一需要担心的是,当requestFailed意外发生时我需要释放请求

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

-(void)sendRequest{

    asiRequest=[[ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://maps.google.com/"]] retain];
    [asiRequest setDelegate:self];
    [asiRequest startAsynchronous];
}

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

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"request Error=%@",[request error]);
}