is there a way to add blocks to NSOperationQueue like this
Asked Answered
T

3

10

I am trying to understand NSOperationQueue's and am trying to create the most simple example possible. I have the following:

NSOperationQueue *myOQ=[[NSOperationQueue alloc] init];

[myOQ addOperationWithBlock:^(void){
  NSLog(@"here is something for jt 2");
}];
[myOQ addOperationWithBlock:^(void){
  NSLog(@"oh is this going to work 2");
}];

But would like to do this:

void  (^jt)() = ^void(){
  NSLog(@"here is something for jt");
};

void (^cl)() = ^void(){
  NSLog(@"oh is this going to work");
};

NSOperationQueue *myOQ=[[NSOperationQueue alloc] init];

[myOQ addOperation:jt];
[myOQ addOperation:cl];

Is this latter form possible? Can I convert a block to an NSOperation?

thx in advance

Trilly answered 11/1, 2013 at 16:38 Comment(2)
No that won't work, but why do you even want to do that? What are you trying to achieve?Eri
just learning with simple example: this was also helpful but read the comments too eng.pulse.me/concurrent-downloads-using-nsoperationqueuesTrilly
G
29

You could:

NSBlockOperation *jtOperation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"here is something for jt");
}];

NSBlockOperation *clOperation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"oh is this going to work");
}];

[myOQ addOperation:jtOperation];
[myOQ addOperation:clOperation];

Having said that, I'd generally do addOperationWithBlock unless I really needed the NSOperation object pointers for some other reason (e.g. to establish dependencies between operations, etc.).

Geotectonic answered 11/1, 2013 at 16:45 Comment(0)
D
3

You can also do

[operationQueue addOperationWithBlock:^{
    // Stuff
})];
Duke answered 5/11, 2015 at 9:19 Comment(0)
S
0

Swift

let networkingOperation = NSBlockOperation(block: {
                             // Your code here
                          })
Stayathome answered 3/4, 2016 at 11:41 Comment(1)
Your solution is tempting, but you should never use NSBlockOperation wrapping an asynchronous function, like a network request. Rather, properly subclass NSOperation. NSOperationQueue is meant to execute asynchronous tasks aka NSOperation instances. The NSBlockOperation is simply a helper where you can enqueue a synchronous operation. In that case, however, you would be almost always better off using dispatch queues.Coughlin

© 2022 - 2024 — McMap. All rights reserved.