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

timpone
  • 19,235
  • 36
  • 121
  • 211
  • No that won't work, but why do you even want to do that? What are you trying to achieve? – Paul.s Jan 11 '13 at 16:41
  • just learning with simple example: this was also helpful but read the comments too http://eng.pulse.me/concurrent-downloads-using-nsoperationqueues/ – timpone Jan 11 '13 at 17:07

3 Answers3

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.).

Duck
  • 34,902
  • 47
  • 248
  • 470
Rob
  • 415,655
  • 72
  • 787
  • 1,044
2

You can also do

[operationQueue addOperationWithBlock:^{
    // Stuff
})];
txulu
  • 1,602
  • 16
  • 26
0

Swift

let networkingOperation = NSBlockOperation(block: {
                             // Your code here
                          })
Oded Regev
  • 4,065
  • 2
  • 38
  • 50
  • 2
    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. – CouchDeveloper Apr 19 '17 at 05:49