【问题标题】:How do I run a process without blocking user interface in my iphone app如何在我的 iphone 应用程序中运行进程而不阻塞用户界面
【发布时间】:2011-11-22 10:07:42
【问题描述】:

我正在访问 iphone 上的照片库,导入我在我的应用程序中选择的图片需要很长时间,我如何在辅助线程上运行该进程,或者我使用什么解决方案来不阻止用户界面?

【问题讨论】:

    标签: iphone objective-c ios multithreading ipad


    【解决方案1】:

    我在这里使用 performSelectOnBackground 或 GCD 对示例代码进行了完整的解释:

    GCD, Threads, Program Flow and UI Updating

    这是该帖子的示例代码部分(减去他的具体问题:

    performSelectorInBackground 示例:

    在这个 sn-p 中,我有一个调用长时间运行的工作的按钮,一个状态标签,我添加了一个滑块来显示我可以在 bg 工作完成时移动滑块。

    // on click of button
    - (IBAction)doWork:(id)sender
    {
        [[self feedbackLabel] setText:@"Working ..."];
        [[self doWorkButton] setEnabled:NO];
    
        [self performSelectorInBackground:@selector(performLongRunningWork:) withObject:nil];
    }
    
    - (void)performLongRunningWork:(id)obj
    {
        // simulate 5 seconds of work
        // I added a slider to the form - I can slide it back and forth during the 5 sec.
        sleep(5);
        [self performSelectorOnMainThread:@selector(workDone:) withObject:nil waitUntilDone:YES];
    }
    
    - (void)workDone:(id)obj
    {
        [[self feedbackLabel] setText:@"Done ..."];
        [[self doWorkButton] setEnabled:YES];
    }
    

    GCD 示例:

    // on click of button
    - (IBAction)doWork:(id)sender
    {
        [[self feedbackLabel] setText:@"Working ..."];
        [[self doWorkButton] setEnabled:NO];
    
        // async queue for bg work
        // main queue for updating ui on main thread
        dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
        dispatch_queue_t main = dispatch_get_main_queue();
    
        //  do the long running work in bg async queue
        // within that, call to update UI on main thread.
        dispatch_async(queue, 
                       ^{ 
                           [self performLongRunningWork]; 
                           dispatch_async(main, ^{ [self workDone]; });
                       });    
    }
    
    - (void)performLongRunningWork
    {
        // simulate 5 seconds of work
        // I added a slider to the form - I can slide it back and forth during the 5 sec.
        sleep(5);
    }
    
    - (void)workDone
    {
        [[self feedbackLabel] setText:@"Done ..."];
        [[self doWorkButton] setEnabled:YES];
    }
    

    【讨论】:

      【解决方案2】:

      使用异步连接。它在后面进行获取时不会阻塞 UI。

      THIS 在我不得不下载图片时帮了我很多忙。

      【讨论】:

        【解决方案3】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-03
          • 2014-11-29
          • 1970-01-01
          • 1970-01-01
          • 2015-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多