简体   繁体   English

Objective-C-sendAsynchronousRequest什么都不做?

[英]Objective-C - sendAsynchronousRequest is doing nothing?

I have this code: 我有以下代码:

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/"]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSLog(@"handler block executed!\n");            
}];

The problem is that the handler blocks is not working. 问题是处理程序块不起作用。 It never executes. 它永远不会执行。

I have read on Xcode docs this: 我已经在Xcode文档上阅读过以下内容:

A completion handler block that runs whenever the transfer finishes or fails.

So, why whenever I execute this code, the handler block doesn't run? 那么,为什么每当我执行此代码时,处理程序块都不会运行? It should run even if the call fails, shouldn't it? 即使调用失败,它也应该运行,不是吗?

OK, I found the solution thanks to Kevin. 好的,我感谢凯文找到了解决方案。 The problem was exactly that ARC was deallocating the NSOperationQueue before the handler block call. 问题恰好是在处理程序块调用之前ARC正在取消分配NSOperationQueue I found the snippet on this japanese blog . 我在这个日本博客上找到了摘录。

#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>

int main(int argc, char *argv[])
{
    @autoreleasepool {
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        dispatch_semaphore_t s = dispatch_semaphore_create(0);

        [NSURLConnection sendAsynchronousRequest:request
            queue:queue
            completionHandler:^(NSURLResponse *r, NSData *d, NSError *e) {
            NSLog(@"%@", r);
            dispatch_semaphore_signal(s);
        }];

        dispatch_semaphore_wait(s, DISPATCH_TIME_FOREVER);
        dispatch_release(s); // <= remove this if you are using ARC.
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM