使用performSelectorOnMainThread调用非void函数

时间:2012-05-01 14:35:48

标签: iphone objective-c ios multithreading

正如我问题的标题所说..我试着用performSelectorOnMainThread调用一个非空函数..我的函数返回UIImage,当我这样调用它时:

UImage *img = [self performSelectorOnMainThread:@selector(captureScreen:) withObject:webView waitUntilDone:YES];

它给我一个错误,我有不兼容的分配类型,我也尝试像这样投射

UImage *img = (UIImage*)[self performSelectorOnMainThread:@selector(captureScreen:) withObject:webView waitUntilDone:YES];

我得到语义问题:'void'类型的操作数,需要算术或指针类型

我知道我可以正常调用它,但是我正在尝试一些多线程的东西并且需要它来调用这样的..所以我怎么能防止这个错误呢?

修改:

我尝试在这个函数(captureScreen)中使用GCD,它继续在“viewToCapture”上创建Exc_bad_access ..所以我决定在GCD块中调用父函数

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

dispatch_async(queue, ^{
    [self captureScreenDelayed:pageView];

    dispatch_sync(dispatch_get_main_queue(), ^{
    });
});

和“ captureScreenDelayed :”如下所示

- (void) captureScreenDelayed:(EpubPageViewController*)pageView
{
    if(!pageView)
        pageView = [self currentPageView];

    if(pageView.pageImageView)
        pageView.pageImageView.image = (UIImage*)[self performSelectorOnMainThread:@selector(captureScreen:) withObject:webView waitUntilDone:YES];
}

captureScreen

-(UIImage*)captureScreen:(UIView*) viewToCapture
{

    UIGraphicsBeginImageContextWithOptions(viewToCapture.bounds.size, viewToCapture.opaque, 0.0);
    [viewToCapture.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

老实说我不确定这是否是以分开的线程获取图像的正确方法......我感谢任何建议。

2 个答案:

答案 0 :(得分:4)

您必须记住的是,您实际调用的方法是-performSelectorOnMainThread:withObject:waitUntilDone:,其返回类型为(void)。因此,您无法获得通过此方法返回的已执行选择器的结果。如果您需要执行此类多线程,则应查看concurrency programming guide,尤其是grand central dispatch

答案 1 :(得分:4)

performSelectorOnMainThread:...没有返回值。您需要找到一些其他机制来恢复图像。一种简单的方法,在这种情况下,因为你正在等待选择器完成,将是通过一个NSMutableArray作为你的对象,并在主线程中添加图像,例如。

NSMutableArray* parameterArray = [[NSMutableArray alloc] init];
[parameterArray addObject: webView];
[self performSelectorOnMainThread:@selector(captureScreen:) withObject:parameterArray waitUntilDone:YES];
if ([parameterArray count > 1)
{
    UIImage* img = [webView objectAtIndex: 1];
}
else
{ 
// error
}

captureScreen:看起来像

-(void) captureScreen: (NSMutableArray*) parameterArray
{
    UIView* webView = [parameterArray objectAtIndex: 0];
    // capture the screen
    [parameterArray addObject: capturedImage];
}