我如何在不阻止iPhone应用程序中的用户界面的情况下运行一个进程

问题描述:

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

我没有使用performSelectOnBackground或GCD这里的示例代码的完整解释:

GCD, Threads, Program Flow and UI Updating

下面是该职位(减去他的具体问题的示例代码部分:

performSelectorInBackground示例:

在这段代码中,我有一个调用长时间运行的工作的按钮,一个状态标签,我添加了一个滑块来显示我可以在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]; 
} 
+0

sleep()仍然锁定主线程但是GDC没有:) –

使用异步连接。它不会阻止用户界面,但它可以在后台进行抓取。

THIS帮助我很多时,我不得不下载图像,其中很多。

+0

退房块和GCD。非常酷 – bryanmac

+0

@bryanmac,很酷的代码! –