NSOperationQueue的addOperationWithBlock的局部块变量

时间:2014-10-13 03:07:12

标签: ios nsoperation nsoperationqueue

如何将局部块变量offDownloadBlock用于NSOperationQueue的addOperationWithBlock方法?

void (^offDownloadBlock)(NSString*, NSDictionary*);
offDownloadBlock = ^(NSString* key, NSDictionary* obj) {...};

NSOperationQueue *q = [[NSOperationQueue alloc] init];
[q addOperationWithBlock:offDownloadBlock(key, obj)];

1 个答案:

答案 0 :(得分:0)

没有理由这样做。 NSOperationQueue的-addOperationWithBlock:定义为- (void)addOperationWithBlock:(void (^)(void))block,这意味着该块不带任何参数并且不返回任何内容。您可以在代码中使用它,如下所示:

NSString *key = @"Some key";
NSDictionary *obj = // Some dictionary;
[q addOperationWithBlock:^(){
    // your code goes here
    // use your key and obj here to do something that will run on the queue
}];

编辑注释:如果要创建递归块,则必须在块内调用块。做这种事情的唯一方法是像这样定义你的块:

__block void (^myBlock)();
myBlock = ^(){
    NSLog(@"Running"); // This will run forever
    myBlock();
};
myBlock();

我会说这可能不是你想要做的事情,但几乎无论如何。