Performing block operations on objects in an array and completing when everything is complete

I have an array of objects on which I would like to perform operations with blocks. I am not sure if this is the best way to do this. I am doing something like the code below, but I don't think this is the best practice. What is the best way to perform such an operation?

- (void)performBlockOnAllObjects:(NSArray*)objects completion:(void(^)(BOOL success))completionHandler {
    NSInteger counter = objects.count;
    for (MyObject *obj in objects) {
        [obj performTaskWithCompletion:^(NSError *error) {
            counter--;
            if (counter == 0) {
                completionHandler(YES);
            }
        }];    
    }
}
+4
source share
1 answer

. "enter" , , "" , , , , "enter" "".

- (void)performBlockOnAllObjects:(NSArray*)objects completion:(void(^)(BOOL success))completionHandler {

    dispatch_group_t group = dispatch_group_create();

    for (MyObject *obj in objects) {
        dispatch_group_enter(group);
        [obj performTaskWithCompletion:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        completionHandler(YES);
    });
}

, , .

+6

Source: https://habr.com/ru/post/1622236/


All Articles