I have no problem to run the sample code below in a iPhone simulator, but when I run it in a iPhone , I always get a EXC_BAD_ACCESS when I call [asiRequest cancel]. anyone can help? thanks.
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;
}
After checking the api, I think I shouldn’t release it in requestFinished or requestFailed
by how can I release it when it finishs?
- (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];
}
You need to retain your ASIHTTPRequest. Because the request was autoreleased via the use of a convenience constructor, you must retain it for it to stick around passed the end of the current run loop.
In addition, do note that you don’t need to check if
asiRequestis notnilincancel1:: sending a message to nil does nothing, and has no adverse effects.