I'm trying to create a NSOperationQueue and add a NSOperation to it. Later I wan't to check if the queue is running and maybe abort it. All of that is supposed to be called from within different functions. What's the best approach to do this? I would be glad for a code example. Thanks!
I would create an operation queue that's managed by a singleton.
First, create your singleton class. It will provide access to the NSOperationQueue. Let's call the singleton MyGlobalQueueManager.
It will have an ivar called myGlobalQueue:
@property (nonatomic) NSOperationQueue* myGlobalQueue;
In the .m file of MyGlobalQueueManager, create a fairly standard init method that will set up the operation queue:
- (id)init
{
self = [super init];
if (self)
{
myGlobalOperationQueue = [[NSOperationQueue alloc] init];
}
return self;
}
Now, the method that provides itself as a singleton. Again, this is pretty standard stuff:
+ (MyGlobalQueueManager *)sharedInstance
{
static MyGlobalQueueManager *sharedInstance = nil;
static dispatch_once_t isDispatched;
dispatch_once(&isDispatched, ^
{
sharedInstance = [[MyGlobalQueueManager alloc] init];
});
return sharedInstance;
}
Let's access that queue from wherever you want to use it:
MyGlobalQueueManager* myGlobalQueueManager = [MyGlobalQueueManager sharedInstance];
NSOperationQueue *myGlobalQueue = myGlobalQueueManager.myGlobalOperationQueue;
You can then add operations to that queue as you fancy.
How to know if anythings queued?
NSUInteger count = [myGlobalQueue operationCount];
How to abort? Cancel everything as follows:
[myGlobalQueue cancelAllOperations];
Cancelling of course depends on the operations. If you're writing custom NSOperation classes, you'll need to handle that yourself.
I find NSOperation and NSOperationQueue to be fairly easy to use and quite straightforward.
A great document to read for all this is the Concurrency Programming Guide. Specifically, have a look at Operation Queues
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With