How to tell if blocks in loop all have completed executing?

前端 未结 4 1936
一个人的身影
一个人的身影 2020-12-02 19:10

I have a loop set up that downloads a series a images which I will later use for to animate using the animationImages property of UIImageView. I wo

4条回答
  •  隐瞒了意图╮
    2020-12-02 19:55

    Create a dispatch group, in the for loop enter the group, in the completion block leave the group. Then you can use dispatch_group_notify to find out when all blocks have completed:

    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
    });
    

提交回复
热议问题