【问题标题】:NSOperationQueue currentQueue not workingNSOperationQueue currentQueue 不工作
【发布时间】:2015-11-11 01:05:49
【问题描述】:

我试图在 currentQueue 上运行AFURLConnectionOperation,因为我想让我的主线程保持空闲以供用户交互,但是当我调用 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

【问题讨论】:

    标签: ios objective-c afnetworking nsoperationqueue


    【解决方案1】:

    原因是

    您可以在正在运行的操作对象中使用此方法来获取对启动它的操作队列的引用。从正在运行的操作的上下文之外调用此方法通常会导致返回 nil。

    所以,我猜,如果你登录[NSOperationQueue currentQueue],它是零

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

    [[NSOperationQueue alloc] init];
    

    【讨论】:

    • 那么如果我创建自己的 NSOperationQueue 不会在主线程上运行?
    • 我不知道你有什么问题,操作是异步的,它不会冻结主线程。
    【解决方案2】:

    在队列上添加操作后,如果操作最终没有开始,那么有两种方法可以让它们执行。

    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(),成功执行当前队列中的当前操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 2013-11-03
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多