4

我有一个代码块,它遍历一个数组并在其上执行块代码。目前它看起来像这样:

for (NSString *myString in myArray) {

    [self doSomethingToString:myString WithCompletion:^(BOOL completion) {
        string = [NSString stringByAppendingString:@"Test"];
    }];

}

我想在开始下一个迭代之前等待上一个迭代完成。我怎样才能遍历这样的块代码?

4

3 回答 3

9

尝试这个

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);

    for (NSString *myString in myArray) {

        [self doSomethingToString:myString WithCompletion:^(BOOL completion) {
            string = [NSString stringByAppendingString:@"Test"];
            dispatch_semaphore_signal(sema);
        }];

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);

    }
于 2013-11-08T11:16:38.837 回答
0

您可以使用

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
   string = [NSString stringByAppendingString:@"Test"];
}];
于 2013-11-08T11:10:16.080 回答
0

斯威夫特 3.1

var sema = DispatchSemaphore(value: 0)
for myString: String in myArray {
    doSomething(to: myString, withCompletion: {(_ completion: Bool) -> Void in
        string = String + ("Test")
        dispatch_semaphore_signal(sema)
    })
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
    dispatch_release(sema)
}
于 2017-05-26T21:06:58.367 回答