iOS:如何在主线程上获取后台线程重绘视图

时间:2012-11-21 21:21:07

标签: ios multithreading setneedsdisplay

我的应用程序将查询数据库50次,然后通过将正确的UIImageView添加到另一个UIImageView来做出相应的反应,然后我希望应用程序立即显示在每个循环中。

唉,经过很多个夜晚,我没能让它上班。应用程序不会立即显示UIImageView。话虽如此,当我在中间循环中放大或缩小时,UIImageViews会出现!我一定错过了什么......

到目前为止,除了最后一部分[UIScrollView performSelector ....

之外,每个代码都有效

请提前帮助并表示感谢。

    UIScrollView *firstView;
    UIImageView *secondView;
    UIImageView *thirdView;
    NSOperationQueue *queue;
    NSInvocationOperation *operation;

    - (void)viewDidAppear:(BOOL)animated
    {
    queue = [NSOperationQueue new];
    operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(getData) object:nil];
    [queue addOperation:operation];
    }

    - (void) getData
    {
     for (i=0 ; i < 50 ; i++)

         {

            //All the codes to facilitate XML parsing here
            [nsXMLParser setDelegate:parser];
            [BOOL success = [nsXMLParser parse];

            if (success) 
            {   

                if ([parser.currentValue isEqualToString:@"G"])

                thirdView.image = greenTick.jpg;
                [secondView addSubview:thirdView];

            } 
            else 
            {
                NSLog(@"Error parsing document!");
            }
    } 
    [thirdView performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone: YES];
}

1 个答案:

答案 0 :(得分:2)

我发现了解决方案并真正希望这能帮助某人......

        if (success) 
        {   

            if ([parser.currentValue isEqualToString:@"G"])

            // Make the changes here - start
            dispatch_queue_t main_queue = dispatch_get_main_queue();
            dispatch_async(main_queue, ^{
            thirdView.image = greenTick.jpg;
            [secondView addSubview:thirdView];
            });
            // Make the changes here - end
        } 
        else 
        {
            NSLog(@"Error parsing document!");
        }
} 
// Remove performSelectorOnMainThread