有没有办法像这样向NSOperationQueue添加块

时间:2013-01-11 16:38:11

标签: ios nsoperationqueue block

我正在尝试了解NSOperationQueue,并尝试创建最简单的示例。我有以下内容:

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");
}];

但是想这样做:

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];

后一种形式可能吗?我可以将块转换为NSOperation吗?

事先提前

3 个答案:

答案 0 :(得分:29)

你可以:

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];

话虽如此,我通常会addOperationWithBlock,除非我出于其他原因需要NSOperation对象指针(例如,建立操作之间的依赖关系等)。

答案 1 :(得分:2)

您也可以

[operationQueue addOperationWithBlock:^{
    // Stuff
})];

答案 2 :(得分:0)

<强>夫特

let networkingOperation = NSBlockOperation(block: {
                             // Your code here
                          })