【问题标题】:Asynchronously load UIViews异步加载 UIViews
【发布时间】:2024-01-22 04:39:01
【问题描述】:

我正在尝试异步加载视图。问题是要加载的视图的框架取决于异步加载的数据。换句话说,有一些冗长的计算决定了实际显示 UIView 的位置。

我知道尝试在线程中实际显示 UIView 时会出现问题,并且您应该始终将它们加载回主线程中,所以这是我一直在尝试的代码:

asyncQueue = [[NSOperationQueue alloc] init];
[asyncQueue addOperationWithBlock:^{
    // Do work to load the UIViews and figure out where they should be
    UIButton *test = [[UIButton alloc] initWithFrame:[self doWorkToGetFrame]];

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self addSubview:test];
        }
    }];
}];

这一切都驻留在 UIView 容器中。

【问题讨论】:

  • 你的问题到底是什么?
  • Apple 说 UIKit 不是线程安全的。这意味着加载包含 UI 元素的笔尖(至少对我而言)。为什么不在操作或块中进行所有计算,然后在后台并发运行,但将结果发布到可以加载、配置和显示实际视图的主线程。在线程中使用 UIKit 做任何事情现在可能会工作,但会在 iOS 的下一个版本中中断。你肯定可以按照我的建议重构你的代码。
  • 我一定会试一试,在过去发生这种情况时,添加到主队列中的部分内容会在其他内容之后显示几秒钟,但我会尝试放置数组中的所有必要参数,然后将视图本身加载到 mianQueue

标签: ios multithreading uiview asynchronous nsoperationqueue


【解决方案1】:

试试这样的:

UIButton *test = [[UIButton alloc] initWithFrame:CGRectZero];
test.hidden = YES;
test.alpha = 0.0f;
[self addSubview:test];

dispatch_queue_t downloadQueue = dispatch_queue_create("myDownloadQueue",NULL);
dispatch_async(downloadQueue, ^
{
  // do work to load UIViews and calculate frame
  CGRect frameButton = ...;

  dispatch_async(dispatch_get_main_queue(), ^
  {
    test.hidden = NO; 
    [UIView animateWithDuration:0.4f animations:^
    {
     test.frame = frameButton;
     test.alpha = 1.0f;
    } 
    completion:^(BOOL finished){}];


  });
});

dispatch_release(downloadQueue);

这会将您的按钮添加到主线程中,但最初使其不可见。后台工作完成后,您将使其可见并使用动画设置框架。

【讨论】:

  • 对,这基本上就是我最终要做的!谢谢!