开发者

NSURLConnection still calls delegate AFTER cancel method has been called

开发者 https://www.devze.com 2022-12-24 22:40 出处:网络
Having a problem with NSURLConnection, if I create a NSURLConnection and call [connection conn开发者_如何转开发ectionWithRequest] let it load a little then call [connection cancel] most of the time th

Having a problem with NSURLConnection, if I create a NSURLConnection and call [connection conn开发者_如何转开发ectionWithRequest] 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.

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 :(


You should not release the connection & associated storage until your delegate receives either a connectionDidFinishLoading: or a connectionDidFailWithError: message.

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.


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.

- (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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号