我会创建一个由单例管理的操作队列。
首先,创建你的单例类。它将提供对NSOperationQueue 的访问。我们称单例为MyGlobalQueueManager。
它将有一个名为myGlobalQueue的ivar:
@property (nonatomic) NSOperationQueue* myGlobalQueue;
在MyGlobalQueueManager的.m文件中,创建一个相当标准的init方法来设置操作队列:
- (id)init
{
self = [super init];
if (self)
{
myGlobalOperationQueue = [[NSOperationQueue alloc] init];
}
return self;
}
现在,提供自己作为单例的方法。同样,这是非常标准的东西:
+ (MyGlobalQueueManager *)sharedInstance
{
static MyGlobalQueueManager *sharedInstance = nil;
static dispatch_once_t isDispatched;
dispatch_once(&isDispatched, ^
{
sharedInstance = [[MyGlobalQueueManager alloc] init];
});
return sharedInstance;
}
让我们从您想使用的任何地方访问该队列:
MyGlobalQueueManager* myGlobalQueueManager = [MyGlobalQueueManager sharedInstance];
NSOperationQueue *myGlobalQueue = myGlobalQueueManager.myGlobalOperationQueue;
然后,您可以根据需要向该队列添加操作。
如何知道是否有任何东西在排队?
NSUInteger count = [myGlobalQueue operationCount];
如何中止?取消一切如下:
[myGlobalQueue cancelAllOperations];
取消当然取决于操作。如果您正在编写自定义 NSOperation 类,则需要自己处理。
我发现NSOperation 和NSOperationQueue 相当容易使用且非常简单。
并发编程指南是一个值得阅读的好文档。具体看Operation Queues