简体   繁体   English

NSURLConnection仍然调用委托AFTER cancel方法已被调用

[英]NSURLConnection still calls delegate AFTER cancel method has been called

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. NSURLConnection遇到问题,如果我创建一个NSURLConnection并调用[connection connectionWithRequest],让它加载一点,然后在大多数情况下都可以调用[connection cancel]。 However occasionally even after I call [connection cancel] the connection's delegate still gets called (which crashes the app). 但是有时即使我调用了[connection cancel],连接的委托仍然会被调用(这会使应用程序崩溃)。 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. 遍历它似乎是问题所在,这是运行循环中的竞争条件,我取消了连接并释放了委托,但是在运行循环之前,它调用了委托函数->崩溃。

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 :( 即使糟糕的while()循环也可以做到:(

You should not release the connection & associated storage until your delegate receives either a connectionDidFinishLoading: or a connectionDidFailWithError: message. 在委托接收到connectionDidFinishLoading: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仍在引用该委托,否则该委托不应变为无效,除非您以某种方式过度释放了它。

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. 由于所有委托方法都将调用Connection对象作为参数接收,并且您还知道实际的活动Connection对象(或nil),因此只需通过比较两个对象来忽略委托操作。 This way a cancelled "ghost" Connection object can still call the delegate but not interfere with its internals. 这样,已取消“鬼”连接对象仍然可以调用委托,但不会干扰其内部。

- (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是您的委托中设置为活动Connection的属性,或者为nil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM