作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在 iphone 上访问照片库,导入我在我的应用程序中选择的图片需要很长时间,我如何在辅助线程上运行该进程,或者我使用什么解决方案来不阻止用户界面?
最佳答案
我在此处使用 performSelectOnBackground 或 GCD 对示例代码进行了完整解释:
GCD, Threads, Program Flow and UI Updating
这是该帖子的示例代码部分(减去他的具体问题:
performSelectorInBackground 示例:
在这个片段中,我有一个调用长时间运行的工作的按钮,一个状态标签,我添加了一个 slider 来显示我可以在 bg 工作完成时移动 slider 。
// 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 - 如何在不阻塞 iPhone 应用程序中的用户界面的情况下运行进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7508246/
我是一名优秀的程序员,十分优秀!