xcode NSURLConnection 在调用取消方法后仍然调用委托
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2503652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSURLConnection still calls delegate AFTER cancel method has been called
提问by Shizam
Having a problem with NSURLConnection, if I create a NSURLConnection and call [connection connectionWithRequest] let it load a little then call [connection cancel] most of the time that works fine. However occasionally even after I call [connection cancel] the connection's delegate still gets called (which crashes the app). Googling around it looks like the problem here is a race condition in the runloop, I cancel the connection and release the delegate but before the runloop cycles it calls the delegate functions -> crash.
NSURLConnection 有问题,如果我创建一个 NSURLConnection 并调用 [connection connectionWithRequest] 让它加载一点然后调用 [connection cancel] 大部分时间都可以正常工作。然而,有时即使在我调用 [connection cancel] 之后,连接的委托仍然会被调用(这会导致应用程序崩溃)。谷歌搜索看起来这里的问题是runloop中的竞争条件,我取消了连接并释放了委托,但在runloop循环之前它调用了委托函数->崩溃。
Is there a way for me to, after I call [connection cancel] confirm the connection has actually canceled? Even a crappy while() loop will do :(
在我拨打 [connection cancel] 确认连接实际上已取消后,我有什么办法吗?即使是蹩脚的 while() 循环也能做到 :(
回答by David Gelhar
You should not release the connection & associated storage until your delegate receives either a connectionDidFinishLoading:
or a connectionDidFailWithError:
message.
在您的代表收到 aconnectionDidFinishLoading:
或connectionDidFailWithError:
消息之前,您不应释放连接和关联的存储。
Delegates are not normally retained by the object they're acting as delegate for. However in this case it is, so the delegate should not become invalid while the NSURLConnection is still referring to it, unless you're over-releasing it somehow.
委托通常不会被它们作为 的委托的对象保留。然而,在这种情况下,当 NSURLConnection 仍在引用它时,委托不应变为无效,除非您以某种方式过度释放它。
回答by Ivan Dossev
I have not yet run into this problem, but this could also work without tying up your delegate object:
我还没有遇到这个问题,但这也可以在不绑定你的委托对象的情况下工作:
Since all delegate methods receive the calling Connection object as a parameter and you also know your actual active Connection object (or nil), simply ignore the delegation actions by comparing the two objects. This way a cancelled "ghost" Connection object can still call the delegate but not interfere with its internals.
由于所有委托方法都接收调用 Connection 对象作为参数,并且您还知道实际活动的 Connection 对象(或 nil),因此只需通过比较两个对象来忽略委托操作。这样,取消的“幽灵” Connection 对象仍然可以调用委托,但不会干扰其内部结构。
- (void) connection:(NSURLConnection*) connection didReceiveData:(NSData*) data
{
if(connection != _URLConnection){return;}
...
[_incomingData appendData:data];
...
}
where _URLConnection
is a property in your delegate set to an active Connection, or nil.
_URLConnection
您的委托中的属性在哪里设置为活动连接,或为零。