如何在不阻止我的iphone应用程序中的用户界面的情况下运行流程 [英] How do I run a process without blocking user interface in my iphone app

查看:116
本文介绍了如何在不阻止我的iphone应用程序中的用户界面的情况下运行流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am accessing the photo library on the iphone and it takes a long time to import the pictures i select in my application, how do i run the process on a secondary thread , or what solution do i use to not block the user interface?

推荐答案

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

I did a full explanation with sample code using performSelectOnBackground or GCD here:

GCD,主题,程序流程和UI更新

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

Here's the sample code portion of that post (minus his specific problems:

performSelectorInBackground示例:

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

In this snippet, I have a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.

// 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];
}

这篇关于如何在不阻止我的iphone应用程序中的用户界面的情况下运行流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆