【问题标题】:Why are my NSURLConnection delegation methods not called?为什么我的 NSURLConnection 委托方法没有被调用?
【发布时间】:2012-07-05 03:56:09
【问题描述】:

我完全按照this official documentation 的指示做了。我创建了一个控制台项目用于测试目的。然后我创建了一个名为 RequestSender 的类(参见下面的代码),并在主函数中创建了这个类的一个实例。

RequestSender.h:

#import <Foundation/Foundation.h>
@interface RequestSender : NSObject <NSURLConnectionDelegate> {
    NSMutableData* d;
}
@end

RequestSender.m:

#import "RequestSender.h"

@implementation RequestSender

- (id)init {
    self = [super init];
    if (self) {
        NSString* s = @"http://www.apple.com/";
        NSURL* u = [[NSURL alloc] initWithString:s];
        NSURLRequest* r = [[NSURLRequest alloc] initWithURL:u];
        NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self];
        if (c) {
            d = [NSMutableData data];
        }

        return self;
    } else {
        return nil;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [d setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [d appendData:data];
}

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

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}


@end

这无疑会在主线程和默认运行循环中执行。然而,没有调用委托方法。

我做了很多测试并阅读了很多帖子,但我仍然没有任何线索。

请帮助我。这让我发疯。 谢谢!

【问题讨论】:

  • 您的代码看起来不错。你怎么称呼它?它是如何嵌入到您的应用中的?
  • 您的代码绝对正确。检查自我是否为空?
  • @Code :它还没有在我的应用程序中。我创建了一个控制台项目来测试它。所有文件都在上面列出。唯一的额外代码在 main 函数中,类似于“RequestSender* rs = [[RequestSender alloc] init];”。我在每个委托方法上都添加了断点,但没有一个被捕获。
  • @PrasadG :你认为这与我使用控制台项目有关吗?
  • @Jack Jiang:是的。如果 self 为 nil,则无法调用委托方法。

标签: xcode multithreading nsurlconnection delegation


【解决方案1】:

我相信你错过了开始连接的部分。连接类为此提供了另一种方法,或者您可以从“c”对象中调用它。

NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self];
if (c) {
    d = [NSMutableData data];
    [c start];
}

或

NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self startImmediately:YES];
if (c) {
    d = [NSMutableData data];
}

【讨论】:

  • 另外,哇——没想到这个问题已经这么老了。我希望你能够修复它,而不是等待答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
相关资源
最近更新 更多