对数组中的对象执行块操作,并在完成所有操作时完成 [英] Performing block operations on objects in array and completing when all complete

查看:124
本文介绍了对数组中的对象执行块操作,并在完成所有操作时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想在其上执行块操作。我不确定这样做的最好方法。我正在做类似下面的代码,但我不认为这是最好的做法。
执行此类操作的最佳方法是什么?

I have an array of objects on which I would like to perform block operations. I am not sure the best way to do this. I am doing something like in the code below but I don't think this is the best practice. What is the best way to do 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);
            }
        }];    
    }
}


推荐答案

你会为此使用调度组。在调用方法之前输入组,在完成处理程序中离开,然后指定当组通知您所有进入调用已通过离开调用进行偏移时应调用的块。

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.

这篇关于对数组中的对象执行块操作,并在完成所有操作时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆