如何判断循环中的块是否都已完成执行?

时间:2014-04-23 19:11:00

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

我有一个循环设置,可以下载一系列图像,我稍后会使用animationImages UIImageView属性来设置动画。我想知道我的循环中的所有块何时完成执行所以我可以开始动画,并且想知道我怎么能够告诉他们什么时候完成完成?谢谢!

for (PFObject *pictureObject in objects){

    PFFile *imageFile = [pictureObject objectForKey:@"image"];
    NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];

    [tokenImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
       [self.downloadedUIImages addObject:image]; //This is a mutableArray that will later be set to an UIImageView's animnationImages

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"Error %@", error);
    }];

}
//When I know all the blocks have finished downloading, I will then to animate the downloaded images. 

修改:遇到Error -999

的问题

我在提供的答案中执行代码时遇到以下问题:Domain=NSURLErrorDomain Code=-999 "The operation couldn’t be completed. (NSURLErrorDomain error -999.)"

快速搜索revealsError -999表示" 在上一个请求完成之前发出另一个请求" ......这是肯定的情况因为我连续几次提出要求。建议修复建议here对我来说不起作用,因为它只会成功下载一个UIImage(最后一个请求),而之前的失败。我想知道这里是否有解决方法或AFNetworking我应该考虑?谢谢!

编辑2:基于@David的解决方案

的工作代码
for (PFObject *pictureObject in objects){

    PFFile *imageFile = [pictureObject objectForKey:@"image"];
    NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:imageRequest];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];

    dispatch_group_enter(group);
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", responseObject);
        UIImage *retrivedImage = (UIImage *)responseObject;
        [self.downloadedUIImages addObject:retrivedImage];

        dispatch_group_leave(group);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image error: %@", error);

        dispatch_group_leave(group);
    }];

    [requestOperation start];
    counter ++;
}

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"Horray everything has completed");
    NSLog(@"What is here %@", self.downloadedUIImages);
    NSLog(@"Done");

});

4 个答案:

答案 0 :(得分:34)

创建一个调度组,在for循环中输入该组,在完成块中离开该组。然后,您可以使用dispatch_group_notify找出所有块何时完成:

dispatch_group_t    group = dispatch_group_create();

for (PFObject *pictureObject in objects){

    PFFile *imageFile = [pictureObject objectForKey:@"image"];
    NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];

    dispatch_group_enter(group);
    [tokenImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        [self.downloadedUIImages addObject:image]; //This is a mutableArray that will later be set to an UIImageView's animnationImages
        dispatch_group_leave(group);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"Error %@", error);
        dispatch_group_leave(group);
    }];

}

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    // do your completion stuff here
});

答案 1 :(得分:2)

计算您已完成的人数。具有挑战性的部分是使其线程安全。我建议为此创建一个原子计数器类。

通用解决方案!

+ (void)runBlocksInParallel:(NSArray *)blocks completion:(CompletionBlock)completion {
    AtomicCounter *completionCounter = [[AtomicCounter alloc] initWithValue:blocks.count];
    for (AsyncBlock block in blocks) {
        block(^{
            if ([completionCounter decrementAndGet] == 0) {
                if (completion) completion();
            }
        });
    }
    if (blocks.count == 0) {
        if (completion) completion();
    }
}

NSMutableArray *asyncBlocks = [NSMutableArray array];
for (PFObject *pictureObject in objects){
    [asyncBlocks addObject:^(CompletionBlock completion) {
        PFFile *imageFile = [pictureObject objectForKey:@"image"];
        NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
        NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];

        [tokenImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
           [self.downloadedUIImages addObject:image]; //This is a mutableArray that will later be set to an UIImageView's animnationImages
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            NSLog(@"Error %@", error);
        } completion:completion];
    }];
}
[BlockRunner runBlocksInParallel:[asyncBlocks copy] completion:^{
    //Do your final completion here!
}];

答案 2 :(得分:0)

设置属性并将其初始化为周期数 - objects.count。在完成块时,降低数字。当你达到零时,你就完成了。

答案 3 :(得分:-3)

for (PFObject *pictureObject in objects){

    PFFile *imageFile = [pictureObject objectForKey:@"image"];
    NSURL *imageFileURL = [[NSURL alloc] initWithString:imageFile.url];
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageFileURL];

    [tokenImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
       [self.downloadedUIImages addObject:image]; //This is a mutableArray that will later be set to an UIImageView's animnationImages
       if([[objects lastObject] isEqual:pictureObject]) {
           [self animateImages];
       }
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"Error %@", error);
        if([[objects lastObject] isEqual:pictureObject]) {
           [self animateImages];
       }
    }];

}

- (void)animateImages {
    //do animation here.
}