遗憾NSOperationQueue
的是,我认为 s 顾名思义,只能用作队列,而不是堆栈。为了避免不得不做一大堆手动编组任务,可能最简单的方法是把你的队列当作不可变的并且通过复制来改变。例如
- (NSOperationQueue *)addOperation:(NSOperation *)operation toHeadOfQueue:(NSOperationQueue *)queue
{
// suspending a queue prevents it from issuing new operations; it doesn't
// pause any already ongoing operations. So we do this to prevent a race
// condition as we copy operations from the queue
queue.suspended = YES;
// create a new queue
NSOperationQueue *mutatedQueue = [[NSOperationQueue alloc] init];
// add the new operation at the head
[mutatedQueue addOperation:operation];
// copy in all the preexisting operations that haven't yet started
for(NSOperation *operation in [queue operations])
{
if(!operation.isExecuting)
[mutatedQueue addOperation:operation];
}
// the caller should now ensure the original queue is disposed of...
}
/* ... elsewhere ... */
NSOperationQueue *newQueue = [self addOperation:newOperation toHeadOfQueue:operationQueue];
[operationQueue release];
operationQueue = newQueue;
目前看来,释放仍在工作的队列(就像旧的操作队列会发生的那样)不会导致它取消所有操作,但这不是记录在案的行为,因此可能不值得信赖。如果你想真正安全,key-value 观察operationCount
旧队列上的属性,当它变为零时释放它。