How to make ui responsive all the time and do background updating?

前端 未结 3 565
囚心锁ツ
囚心锁ツ 2020-12-01 13:28

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

3条回答
  •  遥遥无期
    2020-12-01 14:09

    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.

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

提交回复
热议问题