Chaitanya Gupta
Chaitanya Gupta

Reputation: 4053

Run an anonymous block on a specific background thread

At first glance it seemed like an easy question, but I just can't figure how to run an anonymous block on a certain background thread i.e. I am looking for the blocks equivalent of -performSelector:onThread:withObject:waitUntilDone:.

Related: Is it possible to associate a dispatch queue with a certain background thread, just like the main queue is associated with the application's main thread?

Edit Clarified that I am looking to run an anonymous block

Upvotes: 8

Views: 5437

Answers (3)

Chaitanya Gupta
Chaitanya Gupta

Reputation: 4053

I saw this function RunOnThread() recently in Mike Ash's PLBlocksPlayground (zip file, see BlocksAdditions.m):

void RunOnThread(NSThread *thread, BOOL wait, BasicBlock block)
{
    [[[block copy] autorelease] performSelector: @selector(my_callBlock) onThread: thread withObject: nil waitUntilDone: wait];
}

This is what I was looking for.

There are a bunch of other very useful blocks related utilities in PLBlocksPlayground, most of which Mr. Ash explains in this post.

Upvotes: 6

igofed
igofed

Reputation: 1442

If I understand you right you should do this:

dispatch_queue_t thread = dispatch_queue_create("your dispatch name", NULL);
dispatch_async(analyze, ^{
    //code of your anonymous block
});
dispatch_release(thread);

You also can write some method, which will take block to it, but you should know what type of parameters will it holds:

-(void)performBlock:(void (^)(SomeType par1, SomeType par2))block ToData:(Sometype)data;

You can call it with anonymous block:

[something performBlock:^(SomeType par1, SomeType par2){
  //do your stuff
} ToData: data] 

And in method you can call your block as a simple C function:

block(par1, par2);

Upvotes: 5

NSResponder
NSResponder

Reputation: 16861

A block is a function. Call it like you would call any other function.

Upvotes: -1

Related Questions