我有一些代码发送多个ASIHTTPRequests以在视图控制器中上载和下载数据。当视图控制器被取消分配时,应通过将委托设置为nil来清除所有未完成的请求。
- (void)viewDidLoad
{
// send multiple requests
[self sendRequest:someURL];
[self sendRequest:someURL];
[self sendRequest:someURL];
[self sendRequest:someURL];
}
- (void)sendRequest:(NSString*)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
ASINetworkQueue *requestQueue = [ASINetworkQueue queue];
[requestQueue setMaxConcurrentOperationCount:2];
[requestQueue setDelegate:self];
[requestQueue addOperation:request];
[requestQueue go];
}
- (void)dealloc
{
NSLog(@"cancel all operations");
for (ASIHTTPRequest *req in ASIHTTPRequest.sharedQueue.operations)
{
[req cancel];
[req setDelegate:nil];
}
[super dealloc];
}
但是,如果我在所有操作完成之前弹出该视图控制器,则会在ASIHTTPRequest.m中收到“发送到已释放实例的消息”,抱怨委托在下面的代码中消失了。
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)reportFailure
{
***crash here --> if (delegate && [delegate respondsToSelector:didFailSelector]) {
[delegate performSelector:didFailSelector withObject:self];
}
if (queue && [queue respondsToSelector:@selector(requestFailed:)]) {
[queue performSelector:@selector(requestFailed:) withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if(failureBlock){
failureBlock();
}
#endif
}
我该如何解决?
最佳答案
您正在围绕以下代码行为每个请求创建一个新队列:
ASINetworkQueue *requestQueue = [ASINetworkQueue queue];
因此,这里的循环不会遍历请求,因为它遍历了sharedQueue,而不是您创建的新队列:
for (ASIHTTPRequest *req in ASIHTTPRequest.sharedQueue.operations)
如果使用
[request startAynchronous]
而不显式设置其他队列,则请求只会添加到sharedQueue中。关于iphone - 跟踪ASIHTTPRequest的多个实例的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7368832/