开发者

NSURLConnection doesn't call delegate methods

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


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


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];


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


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.


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

For example:

@interface yourClass : NSObject <NSURLConnectionDelegate>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜