且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使 ui 始终响应并进行后台更新?

更新时间:2023-10-02 17:27:22

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