iOS:NSURLConnection sendAsynchronousRequest在NSImageView上的延迟操作

时间:2013-02-27 08:26:06

标签: ios http asynchronous nsurlconnection

我正在发送异步http GET请求,并正确调用completionHandler。像NSLog这样的回调中的代码会运行,因为我可以看到日志中的输出。但是,行:self.imageView.image = nil;在NSLog语句“到达这里”几秒钟后似乎没有生效。有谁知道发生了什么?示例代码如下:

在ViewController.m中:

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation ViewController
@synthesize imageView = _imageView;

-void viewDidLoad {
    // ImageView
    UIImage *image = [UIImage imageNamed:@"test.jpg"];
    self.imageView.backgroundColor = [UIColor blackColor];
    self.imageView.clipsToBounds = YES;
    self.imageView.image = image;
}

-void test {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://someurl"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
    [request setHTTPMethod:@"GET"];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        self.imageView.image = nil;
        NSLog(@"got here");
    }];
}

@end

2 个答案:

答案 0 :(得分:3)

啊,看起来像将队列参数设置为[NSOperationQueue mainQueue]固定在这里:

NSURLConnection sendAsynchronousRequest:queue:completionHandler: making multiple requests in a row?

答案 1 :(得分:3)

正如Undept建议的那样,在主线程上调用thous行。像这样:

dispatch_async (dispatch_get_main_queue (),  ^{
self.imageView2.image = nil;
self.imageView.image = nil;
});