Jonas Anderson
Jonas Anderson

Reputation: 1987

passing data from a block to another with grand central dispatch

I have a top level block where I would like to create a variable and then pass this to a child block.

Do I need to add a retain on the array I'm going to create in the top-level block? Is this thread-safe since I'm creating the data in one and passing it to another?

dispatch_async(myCustomQ, ^{

 NSMutableArray *myArray = [NSMutableArray array];

 // add things to myArray here

 dispatch_async(dispatch_get_main_queue(), ^{
   [[NSNotificationCenter defaultCenter] postNotificationName:@"aMessageToSend"      
        object:myArray];
 });
});

Upvotes: 1

Views: 511

Answers (1)

bbum
bbum

Reputation: 162722

As long as you don't modify myArray after the second block is enqueued via dispatch_async(), then -- yes -- that code is both correct and thread safe.

Note that you are relying on myCustomQ's implied autorelease pool. I would recommend surrounding that block with an autorelease pool (create one at the beginning, drain it at the end after the enqueuing of the main queue block).

Upvotes: 2

Related Questions