xcode - 为什么我的 NSURLConnection 委托(delegate)方法没有被调用?

标签 xcode multithreading nsurlconnection delegation

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

请求发送者.h:

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

请求发送者.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

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

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

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

最佳答案

我相信您缺少开始连接的部分。连接类为此提供了另一种方法,或者您可以从“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];
}

关于xcode - 为什么我的 NSURLConnection 委托(delegate)方法没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337689/

相关文章:

ios - Xcode tableview 图像一次又一次加载

xcode - 为 UIButton 设置图像

c++ - 在搜索时接收 IShellFolder/IShellFolder2 EnumObjects 实现上的父窗口句柄?

ios - NSURLResponse 在模拟器中很快出现,但在实际设备上它会在一段时间后出现或返回 NULL

objective-c - iOS 上的 NSURLConnection 不会尝试缓存大于 50KB 的对象

ios - 上传大视频时网络连接丢失

iphone - NSString 到 UIImage 类型的参数

ios - 如何检测对 UITabBarItem 的双击?

java - 在java中读取 double 可以是线程安全的吗?

python - 同时解析,python