Performing block operations on objects in array and completing when all complete

北战南征 提交于 2019-12-04 11:05:36

Typically you'd use dispatch groups for this. You "enter" the group before you call your method, you "leave" in the completion handler, and then specify a block that should be called when the group notifies you that all "enter" calls have been offset with "leave" calls.

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

This is the typical pattern for specifying a block of code to be called asynchronously when a series of other asynchronous tasks complete.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!