• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - 后台任务完成后如何指示主 UI 线程? (执行SelectorInBackground)

[复制链接]
菜鸟教程小白 发表于 2022-12-12 18:06:30 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

当后台任务完成时,如何在 iPhone 应用程序 IOS 程序中获得主 UI 线程的指示?

背景

  • 我正在尝试根据 How to add a UIActivityIndicator to a splash screen in a iphone application? 的概念设置加载指示器
  • 打算在 AppDelete 中使用“performSelectorInBackground”来加载模型数据
  • 因此,我需要在 RootViewController 中以某种方式告知数据何时在后台完成加载,以便它可以 (a) 使用数据更新 tableview 并 (b) 删除任何事件指示器
  • 我假设这里的处理方式如下:
    • 在 App Delegate 中 didFinishLaunchingWithOptions 将模型数据加载传递到后台
    • AppDelegate 加载 RootViewController 并立即设置事件指示器
    • 在后台加载数据后,它必须以某种方式向 RootViewController(?这个问题的原因)表明它已经完成
    • 第二个问题可能也是当后台任务确实表明它已完成时,RootviewController 如何在尝试禁用事件指示器之前检查 UI 是否已设置(带有事件指示器等)



Best Answer-推荐答案


您可以使用 -performSelectorOnMainThread:withObject:waitUntilDone: 从后台选择器回调到主线程,如下所示:

- (void)loadModel
{
    // Load the model in the background
    Model *aModel = /* load from some source */;

    [self setModel:aModel];
    [self performSelectorOnMainThreadselector(finishedLoadingModel) withObject:nil waitUntilDone:YES];
}

- (void)finishedLoadingModel
{
    // Notify your view controller that the model has been loaded
    [[self controller] modelLoaded:[self model]];
}

更新:更安全的方法是检查 -finishedLoadingModel 以确保您在主线程上运行:

- (void)finishedLoadingModel
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:YES];
    }
    // Notify your view controller that the model has been loaded
    [[self controller] modelLoaded:[self model]];
}

关于iphone - 后台任务完成后如何指示主 UI 线程? (执行SelectorInBackground),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031868/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap