双击识别器不能与NSTimer一起运行

时间:2013-07-30 09:09:04

标签: ios objective-c nstimer grand-central-dispatch uitapgesturerecognizer

我有一个计时器:

[NSTimer scheduledTimerWithTimeInterval:(float)jpegInterval/1000 target:self selector:@selector(jpegDownloaderSelector:) userInfo:url repeats:YES];

jpegDownloaderSelector执行从url获取图像并将其设置为imageView,如下所示:

-(void) jpegDownloaderSelector:(NSTimer*)timer{
    [self performSelectorInBackground:@selector(jpegDownloader:) withObject:(NSString*)[timer userInfo]];
}

-(void) jpegDownloader:(NSString*)imageUrl{
    dispatch_async(dispatch_get_main_queue(), ^{        
       imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://10.8.9.100:509/jpeg"]];
       imageView.image = [UIImage imageWithData:imgData];
    });
}

我还用gestureRecognizer设置了imageView

[imageView addGestureRecognizer:singleTapRecognizer];
[imageView addGestureRecognizer:doubleTapRecognizer];

识别器定义为:

singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(functoCall:)];
singleTapRecognizer.numberOfTapsRequired = 1;
singleTapRecognizer.numberOfTouchesRequired = 1;

doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(funcToCall2:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
doubleTapRecognizer.numberOfTouchesRequired = 1;

我遇到的问题是,当计时器启动时,我双击图像视图,双击识别器没有响应,而是单击响应。

如果我为定时器重复参数设置了NO,则双击响应。因此,我怀疑由于运行由计时器调用的后台功能,双击没有响应。

任何人都建议我可以实现后台功能,并且没有识别双击的问题。

1 个答案:

答案 0 :(得分:2)

执行此操作时:

dispatch_async(dispatch_get_main_queue(), ^{

你将任务推到主线程,只是在很短的延迟之后。因此,您的图像下载在主线程上完成,并阻止所有其他交互。

相反,您应该在后台线程(dispatch_get_global_queue)上运行下载,然后再回到主线程来处理结果。


-(void) jpegDownloader:(NSString*)imageUrl {
    dispatch_async(dispatch_get_global_queue(), ^{        
       imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://10.8.9.100:509/jpeg"]];

       dispatch_async(dispatch_get_main_queue(), ^{
           imageView.image = [UIImage imageWithData:imgData];
       });
    });
}