2014-11-08 49 views
1

之前,我有一个适度的简单的for循环看起来像这样:等待在for循环回调Next循环

for (NSObject *obj in objectsArray) 
{ 
    [DoThingToObject:obj complete:^{ 
     //Do more 
    }]; 
} 

我需要做在我的阵列中的每个对象上的事情。但是,在我开始循环并在第二个对象上做一件事情之前,我需要等待第一个对象发生完成回调。

我该如何简单地等待,然后做循环中的下一个对象?

谢谢。

回答

5

将是巨大的,如果目标C有承诺,但在那之前,我通常处理这样的事情递归,使用输入数组作为一个待办事项列表...

- (void)doThingToArray:(NSArray *)array then:(void (^)(void))completion { 

    NSInteger count = array.count; 
    // bonus feature: this recursive method calls its block when all things are done 
    if (!count) return completion(); 

    id firstThing = array[0]; 
    // this is your original method here... 
    [self doThingToObject:firstThing complete:^{ 
     NSArray *remainingThings = [array subarrayWithRange:NSMakeRange(1, count-1)]; 
     [self doThingToArray:remainingThings then:completion]; 
    }]; 
} 

这工作正常短阵列。让我知道如果数组很大(数千个元素),我可以告诉你如何以不会结束堆栈的方式进行递归(通过使doThing方法采用单个参数并使用performSelector“递归”)。

编辑 - 执行选择器让当前运行循环完成并在下一次将选择器排队。这样可以节省堆栈,因为您在长阵列上递归,但只需要一个参数,所以我们必须通过整合阵列并将参数阻塞到单个集合对象中来使得该方法稍微不可读...

- (void)doThingToArray2:(NSDictionary *)params { 

    NSArray *array = params[@"array"]; 
    void (^completion)(void) = params[@"completion"]; 

    NSInteger count = array.count; 
    // bonus feature: this recursive method calls its block when all things are done 
    if (!count) return completion(); 

    id firstThing = array[0]; 
    // this is your original method here... 
    [self doThingToObject:firstThing complete:^{ 
     NSArray *remainingThings = [array subarrayWithRange:NSMakeRange(1, count-1)]; 
     [self performSelector:@selector(doThingToArray2:) 
        withObject:@{@"array": remainingThings, @"completion": completion} 
        afterDelay:0]; 
    }]; 
} 

// call it like this: 
NSArray *array = @[@1, @2, @3]; 
void (^completion)(void) = ^void(void) { NSLog(@"done"); }; 
[self doThingToArray2:@{@"array": array, @"completion": completion}]; 

// or wrap it in the original method, so callers don't have to fuss with the 
// single dictionary param 
- (void)doThingToArray:(NSArray *)array then:(void (^)(void))completion { 
    [self doThingToArray2:@{@"array": array, @"completion": completion}]; 
} 
+0

OP是否需要最后提到的方法,我很想看到它的快速草图。 – ravron 2014-11-08 23:58:56

+1

@Riley - 当然。请参阅编辑。 – danh 2014-11-09 01:05:41