NSOperationQueue:麻烦理解命令

我无法理解NSOperationQueue工作方式。

说我有:

 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount=1; [queue addOperationWithBlock:^{ [someObject someSelector]; }]; [queue addOperationWithBlock:^{ [someObject anotherSelector]; }]; 

第二个区块甚至在第一个区块完成之前被调用 – 与我想要的相反。 我尝试使用 – performSelectorOnMainThread:withObject:waitUntilDone:相反,但第二个块仍然是首先执行 – 大概是因为块线程没有在主线程上完成,所以它不会被waitUntilDone封锁。 我在我的someSelector块中添加了一个断点,并在第二个块内的断点之后到达。

我不太明白。 帮我!!

如果操作之间有明确的依赖关系,则使用addDependency

 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount=1; NSOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{ [someObject someSelector]; }]; NSOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ [someObject anotherSelector]; }]; [operation2 addDependency:operation1]; [queue addOperation:operation1]; [queue addOperation:operation2]; 

如果您的操作正在执行asynchronous活动,那么您应该定义一个自定义操作,并且只在asynchronous任务完成时调用completeOperation (它将发布isFinished消息)。

 // SomeOperation.h #import <Foundation/Foundation.h> @interface SomeOperation : NSOperation @end 

 // SomeOperation.m #import "SomeOperation.h" @interface SomeOperation () @property (nonatomic, readwrite, getter = isFinished) BOOL finished; @property (nonatomic, readwrite, getter = isExecuting) BOOL executing; @end @implementation SomeOperation @synthesize finished = _finished; @synthesize executing = _executing; #pragma Configure basic operation - (id)init { self = [super init]; if (self) { _finished = NO; _executing = NO; } return self; } - (void)start { if ([self isCancelled]) { self.finished = YES; return; } self.executing = YES; [self main]; } - (void)completeOperation { self.executing = NO; self.finished = YES; } - (void)main { // start some asynchronous operation // when it's done, call `completeOperation` } #pragma mark - Standard NSOperation methods - (BOOL)isConcurrent { return YES; } - (void)setExecuting:(BOOL)executing { [self willChangeValueForKey:@"isExecuting"]; _executing = executing; [self didChangeValueForKey:@"isExecuting"]; } - (void)setFinished:(BOOL)finished { [self willChangeValueForKey:@"isFinished"]; _finished = finished; [self didChangeValueForKey:@"isFinished"]; } @end 

因此,使用下面的代码,直到在SomeOperation对象operation1 main中启动的asynchronous任务调用其completeOperation方法,才会启动operation2

 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount=1; NSOperation *operation1 = [[SomeOperation alloc] init]; NSOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ [someObject anotherSelector]; }]; [operation2 addDependency:operation1]; [queue addOperation:operation1]; [queue addOperation:operation2];