如果在操作之間明確的相關性,然後用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];
如果你的業務是做異步的活動,那麼你應該定義自定義操作,只有調用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
因此,用下面的代碼,它不會開始operation2
直到SomeOperation
對象,operation1
在main
啓動異步任務,調用其completeOperation
方法。
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];
來源
2013-11-26 18:26:12
Rob
我還是不太明白。我應該怎樣對待我的代碼以保證FIFO? – JoshDG
我認爲你必須設置操作依賴來保證操作順序。 –
只要使用'addDependency'就可以完成這項工作,除非這些方法中的任何一個都是異步運行的,在這種情況下,您可能需要使用'NSOperation'子類。 – Rob