iphone - 如何让ui始终响应并进行后台更新?

标签 iphone objective-c cocoa asynchronous

我正在创建一个每页显示 8 个缩略图的应用程序,它可以有 n 个页面。这些缩略图中的每一个都是 UIView 并添加到 UIScrollView 中。不过我已经使用Apple示例代码实现了分页。

问题:

  1. 每个缩略图(UIView)需要150 要创建并添加到的毫秒数 ScrollView
  2. 因此 3 页的内容非常糟糕 需要花费大量时间来创建和添加 UI ScrollView 。
  3. 此时, ScrollView 的响应速度不是很好,而且非常不稳定,用户体验很差
  4. 如何创建缩略图并将其添加到 UIScrollview 而不影响触摸响应能力?我希望它们独立于主线程运行,主线程负责处理触摸事件(我想)。

另外我想提一下,当创建缩略图时,我会触发图像的异步下载,并在下载完成时调用委托(delegate)方法。

让我知道我必须做出哪些选项才能使其响应更快并更新 UI,而不影响触摸操作。页面控件可以很好地延迟加载缩略图网格。

TIA,

普雷文小号

最佳答案

Grand Central Dispatch 易于用于后台加载。但GCD只适用于iOS4之后的版本。如果您必须支持 iOS3,performSelectorInBackground/performSelectorOnMainThread 或 NSOperationQueue 会很有帮助。

并且,请注意,除了绘制到图形上下文之外,几乎 UIKit 类都不是线程安全的。例如,UIScrollView 不是线程安全的,UIImage imageNamed: 不是线程安全的,但 UIImage imageWithContentsOfFile: 是线程安全的。

dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(concurrentQueue, ^{

    dispatch_apply([thumbnails count], concurrentQueue, ^(size_t index) {

        Thumbnail *thumbnail = [thumbnails objectAtIndex:index];
        thumbnail.image = [UIImage imageWithContentsOfFile:thumbnail.url];

        dispatch_sync(mainQueue, ^{

            /* update UIScrollView using thumbnail. It is safe because this block is on main thread. */

        });
    }

    /* dispatch_apply waits until all blocks are done */

    dispatch_async(mainQueue, ^{
        /* do for all done. */
    });
}

关于iphone - 如何让ui始终响应并进行后台更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133731/

相关文章:

iphone - 具有 AND 和 OR 问题的 NSPredicate

ios - Iphone 在当前帧内旋转视频

objective-c - 有什么方法可以监控 Mac 上的新应用程序安装事件吗?

cocoa - 如何在绘制 NSPopUpButton 单元格时手动突出显示它(使用白色而不是黑色绘制)?

ios - Apple 和私有(private) API

iphone - 等待事件播放

iphone - Objective c - NSDictionary 保留对象问题

ios - 在代码中使两个 AutoLayout 约束相等?

objective-c - NSTextView 没有光标,如果它是空的

xcode - NSDistributedNotifications 未在(相同)应用程序的实例之间分发