NSURLConnection doesn't call delegate methods

2019-01-23 04:33发布

I saw similar questions here, but I couldn't find solution to my problem. I have a simple NSURLConnection in main thread (At least I didn't create any other threads), but my delegate methods aren't get called

[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

and no methods called, e.g.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
}

self is also a delegate for NSXMLParser, but I think it should not be a problem, as I have this working in my other class in the same project. I checked everything 10 times already, but can't find any problem.

I've seen some hack to solve it here: http://www.depl0y.com/?p=345 but I don't like it, May be someone knows better solution? thanks

5条回答
何必那么认真
2楼-- · 2019-01-23 05:00

Try running your connection on main thread:

NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request
                                         delegate:self startImmediately:NO];

[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
            forMode:NSDefaultRunLoopMode];
[connection start];
查看更多
对你真心纯属浪费
3楼-- · 2019-01-23 05:09

You have to release the NSURLConnection object in the - (void)connectionDidFinishLoading:(NSURLConnection *)connection callback as pointed out in the Apple documentation, not elsewhere:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  // Do whatever you want here

  // Release the connection
  [connection release];
}

Don't release it with autorelease, as Lou Franco suggested.

If it is not the problem, then maybe you have to implement all the required methods in the delegate class:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

The delegate is retained by NSURLConnection so you don't have to worry about it.

查看更多
SAY GOODBYE
4楼-- · 2019-01-23 05:10

I think you may have missed NSURLConnectionDelegate in your class header file.

For example:

@interface yourClass : NSObject <NSURLConnectionDelegate>
查看更多
乱世女痞
5楼-- · 2019-01-23 05:11

The only reason I know is a separate thread (that is already terminated when the delegate methods are called).

Try to NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));right before the url connection creation

查看更多
虎瘦雄心在
6楼-- · 2019-01-23 05:16

The autorelease is dangerous. The calls to the delegate are made after your function returns (asynchronously). Are you retaining it somewhere else?

查看更多
登录 后发表回答