我有一个ID数组,在其中运行一个for循环,并调用一个在后台运行的方法(进行网络调用以获取数据)。我怎么知道for循环何时完成并且所有调用也都完成了?

目前,for循环已在所有调用完成之前完成。我应该使用while循环吗?

更新(终于成功了!)

我将代码发布在这里,希望对其他人有所帮助。 :)

详细信息:根据Andrey的建议,我要做的第一件事是将NSOperation子类化并执行以下操作:

@interface AsyncOperation ()

@property (atomic, assign) BOOL _executing;
@property (atomic, assign) BOOL _finished;

@end

@implementation AsyncOperation

- (void)start {

    if ([self isCancelled]) {

        //Move the operation to the finished state if it is canceled.
        [self willChangeValueForKey:@"isFinished"];
        self._finished = YES;
        [self didChangeValueForKey:@"isFinished"];
        return;
    }

    //If the operation is not canceled, begin executing the task.
    [self willChangeValueForKey:@"isExecuting"];
    [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
    self._executing = YES;
    [self didChangeValueForKey:@"isExecuting"];

}

- (void)main {
    if ([self isCancelled]) {
        return;
    }
}

- (BOOL)isAsynchronous {
    return YES;
}

- (BOOL)isExecuting {
    return self._executing;
}

- (BOOL)isFinished {
    return self._finished;
}

//Make sure to expose this method in the header file
- (void)completeOperation {

    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];

    self._executing = NO;
    self._finished = YES;

    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}

最后,在我的方法中,我做到了:
    //Setup NSOperation Queue
    self.queue = [[NSOperationQueue alloc] init];
    self.queue.name = @"myQueue";

    //Set Queue Observer (Using Third Party Library KVOController)
    [self.KVOController observe:self.queue keyPath:@"operationCount" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew block:^(id observer, NSOperationQueue *queue, NSDictionary *change) {

        //Check if all operations concluded
        if (queue.operationCount == 0) {

            //Remove Observer
            [self.KVOController unobserve:self.queue];

            //DO SOMETHING NOW THAT EVERYTHING IS DONE
        }
    }];

    //Loop through my chats and fetch each one
    for (NSString *chatId in chatIds) {

        //Observe Operation
        AsyncOperation *operation = [[AsyncOperation alloc] init];
        [self.KVOController observe:operation keyPath:@"isExecuting" options:NSKeyValueObservingOptionNew block:^(id observer, EMKAsyncOperation *myOperation, NSDictionary *change) {

            //Check if operation is executing
            if ([myOperation isExecuting]) {

                //Fetch Chat (My async method)
                [self fetchChatWithId:chatId inBackgroundWithBlock:^(Chat *chat, BOOL succeeded, NSError *error) {

                    //Check for error
                    if (!error) {

                        //DO WHATEVER I DO AFTER FETCHING COMPLETED

                        //Complete operation manually
                        [myOperation completeOperation];

                        //Remove Observer
                        [self.KVOController unobserve:myOperation];

                    } else {

                       //Error Cancel Everything
                       finalError = error;

                       NSLog(@"Error fetching all chats: %@", [error localizedDescription]);

                       //Cancel Operations
                       [self.queue cancelAllOperations];

                        //Complete operation
                        [myOperation completeOperation];

                        //Remove Observer
                        [self.KVOController unobserve:myOperation];
                    }
                }];
            }
        }];

        //Add Operation
        [self.queue addOperation:operation];
    }

希望这对人们有所帮助!

最佳答案

看起来问题不在于找出循环何时结束,这很明显,而在于何时完成所有网络调用。
所以这就是我要做的。我会将每个网络调用包装到NSOperation类的实例中,然后将每个操作添加到NSOperationQueue中。此类具有operationsCount属性,该属性是可观察到的键值。因此,使用KVO可以观察到此属性的变化。一旦operationsCount等于0-完成。所有请求已完成

10-04 21:34
查看更多