使用参数延迟递归方法调用

时间:2014-07-22 18:59:25

标签: ios objective-c objective-c-blocks

我的应用从服务器加载图片。我使用SDWebImage进行缓存。当我尝试显示图像时,如果图像尚未缓存,则显示占位符图像,以便我决定等待它是否未缓存。

- (void)photoPagesController:(EBPhotoPagesController *)controller
            imageAtIndex:(NSInteger)index
       completionHandler:(void (^)(UIImage *))handler
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{

        MyPhoto *photo = self.photos[index];

        [self.manager cachedImageExistsForURL:photo.url completion:^(BOOL isInCache) {

            if (isInCache) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(photo.imageView.image);
                });
            }
            else {
                // Wait 1 second and then call 
                // photoPagesController:imageAtIndex:completionHandler recursively.   
            }  
        }];
    });    

}

等待一定时间后如何进行递归通话? 有没有更好的方法来实现它?

1 个答案:

答案 0 :(得分:1)

使用dispatch_after尝试

- (void)photoPagesController:(EBPhotoPagesController *)controller
            imageAtIndex:(NSInteger)index
       completionHandler:(void (^)(UIImage *))handler
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{

        MyPhoto *photo = self.photos[index];

        [self.manager cachedImageExistsForURL:photo.url completion:^(BOOL isInCache) {

            if (isInCache) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(photo.imageView.image);
                });
            }
            else {
                // Wait 1 second and then call 
                // photoPagesController:imageAtIndex:completionHandler recursively.   
                double delayInSeconds = 1.0;  //Give the delay you want 
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                //This will called after 1 seconds
                [self photoPagesController:controller
                    imageAtIndex:index
                    completionHandler:handler];


              });
            }  
        }];
    });  
}