在等待上一次执行完成时循环通过块

时间:2013-11-08 10:43:30

标签: ios objective-c nsstring nsarray block

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

for (NSString *myString in myArray) {

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

}

我想在开始下一次迭代之前等待上一次迭代完成。我怎样才能像这样循环一些块代码呢?

3 个答案:

答案 0 :(得分:8)

试试这个

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

    }

答案 1 :(得分:0)

你可以使用

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
   string = [NSString stringByAppendingString:@"Test"];
}];

答案 2 :(得分:0)

Swift 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)
}