首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从UIAlertViewDelegate回调返回到后台线程

从UIAlertViewDelegate回调返回到后台线程
EN

Stack Overflow用户
提问于 2012-10-19 01:00:03
回答 1查看 838关注 0票数 1

我有一个导入序列,从存档中读取,解压缩包含的文件,并为每个文件创建相应的核心数据实体。整个过程发生在后台,并且已经为每个线程创建了一个单独的上下文,所以所有这些都很好。

事实证明,这个特定导入序列的一个可取特性是,我们允许任何输入文件受到密码保护(存档中包含了其中的几个),因此我需要检查文件是否受密码保护,在这种情况下,用户将被提示通过UIAlertView输入密码。

这就是我的问题开始的地方。

我将UIAlertView提示符如实发送到主线程,将导入器object指定为delegate,并等待用户输入。

当用户输入密码并点击OK/Cancel时,委托回调仍然在主线程上,因此,如果不进行大量工作(例如存储对托管对象ID的引用、创建新上下文等),我就无法操作相应的核心数据实体。

我的问题:

是否有可能返回导入进程正在工作的原始后台线程?我该怎么做?

谢谢,罗格

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-21 19:14:26

我会尝试使用调度信号量。将其保存在实例变量中。

代码语言:javascript
复制
@interface MyClass ()
{
    dispatch_semaphore_t dsema;
}
@end

然后,在后台线程方法中:

代码语言:javascript
复制
// 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将调用此委托方法:

代码语言:javascript
复制
// 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);
        ...
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12965946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档