基于earlier问题:
我有一个NSOperationQueue看起来像这样:

NSBlockOperation *block1 = [NSBlockOperation blockOperationWithBlock:^{
        [someObject someSelector];
    }];

NSBlockOperation *block2= [NSBlockOperation blockOperationWithBlock:^{
    [someObject anotherSelector];
}];

[block2 addDependency:block1];
[queue addOperation:block1];
[queue addOperation:block2];


现在,在someSelector中,我有:

returnData = [requesterObj getDataWithURL:(NSString*)url];


其中getDataWithURL包含以下内容:

NSURL *requestUrl = [NSURL URLWithString:strUrl];

NSMutableURLRequest *request = [NSMutableURLRequest requestUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];


现在,当我添加断点时,似乎在从第一个块开始的NSURLConnection之前调用了第二个块。大概是因为对getDataWithURL的调用本身是异步的。确保该请求返回之前第一个块未完成的最佳方法是什么。我是否应该尝试使用NSInvocation将数据放入returnData

最佳答案

NSBlockOperation *block1 = [NSBlockOperation blockOperationWithBlock:^{
    [someObject someSelector];
}];


这将创建“标准”块操作。即使从用户的角度来看异步网络操作尚未完成,该操作在块执行后仍被视为已完成([block1 isFinished]为true)。

由于您不希望这样做,因此需要继承NSOperation的子类,并通过覆盖其start明确告诉操作完成的时间:

- (void)completeOperation {

    self.finished = YES;
    self.executing = NO;
}

- (void)start {

    if ([self isCancelled]) {
        [self completeOperation];
        return;
    }

    self.executing = YES;
    [self main];
    // this is where operation is set to finished in NSOperation
}

- (void)main {
    [someObject someSelectorWithCompletionBlock: ^() {
        [self completeOperation];
        // retain cycle may exist unless completion block is destroyed afterwards
    }];
}

关于ios - 具有同步NSURLConnection的NSOperationQueue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20225804/

10-12 14:42