我有一个导入序列,从存档中读取,解压缩包含的文件,并为每个文件创建相应的核心数据实体。整个过程发生在后台,并且已经为每个线程创建了一个单独的上下文,所以所有这些都很好。
事实证明,这个特定导入序列的一个可取特性是,我们允许任何输入文件受到密码保护(存档中包含了其中的几个),因此我需要检查文件是否受密码保护,在这种情况下,用户将被提示通过UIAlertView输入密码。
这就是我的问题开始的地方。
我将UIAlertView提示符如实发送到主线程,将导入器object指定为delegate,并等待用户输入。
当用户输入密码并点击OK/Cancel时,委托回调仍然在主线程上,因此,如果不进行大量工作(例如存储对托管对象ID的引用、创建新上下文等),我就无法操作相应的核心数据实体。
我的问题:
是否有可能返回导入进程正在工作的原始后台线程?我该怎么做?
谢谢,罗格
发布于 2012-10-21 19:14:26
我会尝试使用调度信号量。将其保存在实例变量中。
@interface MyClass ()
{
dispatch_semaphore_t dsema;
}
@end然后,在后台线程方法中:
// this is the background thread where you are processing the archive files
- (void)processArchives
{
...
self.dsema = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: @"Title"
...
delegate: self
...
];
[alertView show];
});
dispatch_semaphore_wait(self.dsema, DISPATCH_TIME_FOREVER);
// --> when you get here, the user has responded to the UIAlertView <--
dispatch_release(self.dsema);
...
}UIAlertView将调用此委托方法:
// this is running on the main queue, as a method on the alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
// do stuff with alertView
if (buttonIndex == [alertView firstOtherButtonIndex]) {
...
// when you get the reply that should unblock the background thread, unblock the other thread:
dispatch_semaphore_signal(self.dsema);
...
}
}https://stackoverflow.com/questions/12965946
复制相似问题