本文介绍了如何让 ui 始终响应并进行后台更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a application which displays 8 thumbnails per page and it can have n pages. Each of these thumbnails are UIViews and are added to UIScrollView. However i have implemented Paging using the Apple sample code.

问题:

  1. 每个缩略图(UIView)需要 150要创建并添加到的毫秒数滚动视图
  2. 因此对于 3 页来说,这太糟糕了需要大量时间来创建和添加UI 滚动视图.
  3. 此时滚动视图的响应速度不快,而且非常生涩,用户体验很差
  4. 如何在不影响触摸响应的情况下创建缩略图并将它们添加到 UIScrollview?我希望它们独立于主线程运行,主线程负责处理触摸事件(我想).

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

Also i would like to mention that when a thumbnail is created i trigger a Async download of the image and the delegate method is called when download is complete.

让我知道在不影响触摸操作的情况下我必须使这个更具响应性和更新 UI 的选项.页面控件在延迟加载缩略图网格时工作正常.

Let me know the the options i have to make this more responsive and update UI without affecting the touch operations. The page control works fine with lazy loading of the grid of thumbnails.

TIA,

Praveen S

推荐答案

Grand Central Dispatch 易于用于后台加载.但 GCD 仅适用于 iOS4 之后.如果你必须支持 iOS3,performSelectorInBackground/performSelectorOnMainThread 或 NSOperationQueue 很有帮助.

Grand Central Dispatch is easy to use for background loading. But GCD is only for after iOS4. If you have to support iOS3, performSelectorInBackground/performSelectorOnMainThread or NSOperationQueue are helpful.

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

And, be careful almost UIKit classes are not thread-safe except drawing to a graphics context. For example, UIScrollView is not thread-safe, UIImage imageNamed: is not thread-safe, but UIImage imageWithContentsOfFile: is thread-safe.

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. */
    });
}

这篇关于如何让 ui 始终响应并进行后台更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:26