2

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

2 回答 2

9

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

另外,请注意,您不需要检查 if asiRequestis not nilin cancel1::向 nil 发送消息什么都不做,也没有负面影响。

于 2010-01-25T00:37:42.550 回答
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]);
}
于 2010-01-25T03:29:57.123 回答