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

Posted

技术标签:

【中文标题】iOS:如何让后台线程在主线程上重绘视图【英文标题】:iOS: How to get background thread to redraw view on main thread 【发布时间】:2012-11-21 21:21:06 【问题描述】:

我的应用程序将查询数据库 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];

【问题讨论】:

thirdView”在哪里分配?你在使用 ARC 吗? 嗨,迈克尔,感谢您的回复。 “第三个视图”在 -(void)viewDidLoad 中分配。像这样 thirdView = [[UIImageView alloc] init];我正在使用 ARC。 【参考方案1】:

我发现了解决方案,并真心希望这对某人有所帮助...

        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 

【讨论】:

以上是关于iOS:如何让后台线程在主线程上重绘视图的主要内容,如果未能解决你的问题,请参考以下文章

如何防止主线程ios杀死后台线程

如何让PhoneGap IOS插件在后台线程中运行

iOS 在后台保存主线程 NSManagedObjectContext 更改

让 UIView drawRect 发生在后台线程中

Android:如何在所有后台线程完成后启用按钮

在主线程外创建 UIImage