NSOperationQueue currentQueue 不工作

NSOperationQueue currentQueue not working

我正在尝试 运行 AFURLConnectionOperation 在 currentQueue 上看到下面的内容,因为我想让我的主线程空闲以供用户交互,但是当我调用 mainQeue 时没有任何反应。

但是,如果我在 mainQueue 上调用相同的 AFURLConnectionOperation,它会完美运行。

请看下面的代码

// Send Batch
        NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
            NSLog(@"%lu of %lu complete", (unsigned long)numberOfFinishedOperations, (unsigned long)totalNumberOfOperations);
        } completionBlock:^(NSArray *operations) {
            // check batch response
            NSError *error;
            for (AFHTTPRequestOperation *op in operations) {
                if (op.isCancelled){
                    return ;
                }
                if (op.responseObject){
                    // Current JSON Batch complete
                    NSMutableArray *jsonObject = [NSJSONSerialization JSONObjectWithData:op.request.HTTPBody options:kNilOptions error:&error];
                    // Update sent_flag using current chunk
                    [[SyncModel sharedInstance] updateSentFlag:jsonObject];
                }
                if (op.error){
                    error = op.error;
                    NSLog(@"Error == %@", error);
                }
            }
        }];

最后我调用了以下代码之一

[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO]; // this works
[[NSOperationQueue currentQueue] addOperations:operations waitUntilFinished:NO]; // this dose not work

原因是

You can use this method from within a running operation object to get a reference to the operation queue that started it. Calling this method from outside the context of a running operation typically results in nil being returned.

所以,我猜,如果你记录 [NSOperationQueue currentQueue],它是 nil

如果你想要一个新队列,使用

[[NSOperationQueue alloc] init];

将操作添加到队列后,如果操作最终没有启动,则有两种方法可以执行它们。

  1. 使用等待块,例如在使用 XCTest 框架进行单元测试时,使用

    XCTestExpectation *expectation1 = [self    expectationWithDescription:@"ExtractColorsInternal function call on     NSOperationQueue"];
     dispatch_async(dispatch_get_main_queue(), ^{
    
    [expectation1 fulfill];
    });
    
    [self waitForExpectationsWithTimeout:1000 handler:^(NSError *error) {
    if (error != nil) {
        NSLog(@"Error: %@", error.localizedDescription);
    }
    }];
    
  2. 调用CFRunLoopRun(),成功执行当前队列中的当前操作