Search code examples
iosnsoperationqueueblock

is there a way to add blocks to NSOperationQueue like this


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


Solution

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