10

我正在尝试了解 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 吗?

提前谢谢

4

3 回答 3

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

于 2013-01-11T16:45:26.030 回答
2

你也可以做

[operationQueue addOperationWithBlock:^{
    // Stuff
})];
于 2015-11-05T09:19:35.167 回答
0

迅速

let networkingOperation = NSBlockOperation(block: {
                             // Your code here
                          })
于 2016-04-03T11:41:45.220 回答